https://leetcode-cn.com/problems/swap-nodes-in-pairs/
思路一:顺着做,这样也有两种做法。第一种就是直接两个两个交换,那么需要记录前驱和后继。第二种就是先把链表分成两个小的链表,一个存储奇数位置的树,一个存储偶数位置的数,然后再把他们合起来。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(!head||!head->next)
return head;
ListNode *pre,*cur=head,*nxt=head->next;
cur->next=nxt->next;
nxt->next=cur;
head=nxt;
pre=cur;
while(pre){
cur=pre->next;
if(!cur||!cur->next)
break;
nxt=cur->next;
cur->next=nxt->next;
nxt->next=cur;
pre->next=nxt;
pre=cur;
}
return head;
}
};
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* merge(ListNode* l,ListNode *r){
ListNode head(0);
ListNode *res=&head;
bool flag=1;
while(l&&r){
if(flag){
res->next=l;
res=l;
l=l->next;
}
else{
res->next=r;
res=r;
r=r->next;
}
flag=!flag;
}
res->next=l?l:r;
return head.next;
}
ListNode* swapPairs(ListNode* head) {
if(!head||!head->next)
return head;
ListNode odd(0),even(0);
ListNode *tail1=&odd,*tail2=&even,*cur=head;
bool flag=1;
while(cur){
if(flag)
tail1->next=cur,tail1=cur;
else
tail2->next=cur,tail2=cur;
cur=cur->next;
flag=!flag;
}
tail1->next=tail2->next=nullptr;
return merge(even.next,odd.next);
}
};
思路二:递归。思路其实和上面的差不多,但是代码相当简洁。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(!head||!head->next)
return head;
ListNode *cur=head;
ListNode *nxt=head->next;
cur->next=swapPairs(nxt->next);
nxt->next=cur;
return nxt;
}
};