单链表的反转
//定义一个链表结点
struct ListNode{
int data;
ListNode* next;
};
(1)头结点插入法
void Reversal(LinkNode* head){
LinkNode *p,*q;
p=head->next;
head->next=NULL;
while(p){
q=p->next;
p->next=head->next;
head->next=p;
p=q;
}
}
(2)三指针法(就地反转法)
void Reversal(struct ListNode* head){
LinkNode *pre,*cur,*next;//cur为当前操作结点,pre为上一个结点,next是下一个结点
pre->next=NULL;
cur=head->next;
while(cur){
next=cur->next;
cur->next=pre;
pre=cur;
cur=next;
}
head->next=pre;
}
(3)递归法
void Reversal(struct ListNode* head){
//终止条件:找到最后一个节点
if(head==NULL||head->next==NULL){
return head;
}else{
ListNode* newhead=Reversal(head->next);//从最后两个开始反转
head->next->next=head;
head->next=NULL;
return newhead;
}
}
单链表的合并
(1)迭代法
struct ListNode* mergeTwoLists(struct ListNode* head1, struct ListNode* head2){
LinkNode *head3;
LinkNode *p,*q,*r;
p=head1->next;
q=head2->next;
r=head3=head1;
while(p&&q){
if(p->data<=q->data){
r->next=p;
r=p;
p=p->next;
}else{
r->next=q;
r=q;
q=q->next;
}
}
if(p) r->next=p;
if(q) r->next=q;
free(head2);
return head3;
}
(2)递归法
struct ListNode* mergeTwoLists(struct ListNode* head1, struct ListNode* head2){
if(!head1) return head2;
if(!head2) return head1;
if (head1->data < head2->data) {
head1->next = mergeTwoLists(head1->next, head2);
return head1;
} else {
head2->next = mergeTwoLists(head1, head2->next);
return head2;
}
}