C++递归法
/** * 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==NULL||head->next==NULL) return head; ListNode* newhead=head->next; head->next=swapPairs(head->next->next); newhead->next=head; return newhead; } };
C++迭代法:代码应该简化下
/** * 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==NULL||head->next==NULL) return head; ListNode* res=head->next; ListNode* ppre,*pre=head,*cur=head->next; while(cur){ if(cur->next==NULL){ cur->next=pre; pre->next=NULL; break; } ppre=pre; pre=cur->next; cur->next=ppre; cur=pre->next; ppre->next=cur; if(cur==NULL){ ppre->next=pre; break; } } return res; } };
C++迭代法进阶一:参考别人python的思路,先在上一轮循环令上一轮的尾节点,也就是前驱pre的pre->next=a,如果本轮循环能够执行,那么再在本轮循环中将pre->next更新为b,这样可以有效解决奇数和偶数节点的两两交换:
-1——1——2——3——x——y
对于这个例子,
先令pre指向-1,由于不知道后面有奇数节点还是偶数节点,先令pre->next指向1;
当pre->next,pre->next->next不为空时(1,和2都是有节点存在的)执行本次循环,令a,b的值分别为2,由于依然不知道后面有奇数节点还是偶数节点,先令a->next=b->next,即令a指向b的下一个元素,也就是先让他指向3(因为如果x存在不为NULL,那么下轮循环可以执行,等到下轮循环中令指向x,否则循环终止),然后翻转令b->next=a,即b下一个值为a。
(如果x!=NULL,比如x为4) 执行第2轮循环,与上述过程相同,a=3,b=x=4, a指向y, b指向3,y=NULL循环结束
即
/** * 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==NULL || head->next==NULL) return head; ListNode *pre=new ListNode(-1),*a,*b,*res;//定义前驱,和交换、返回用的指针变量 pre->next=head;res=head->next;//为前驱指向的下一个节点和返回节点赋值; while(pre->next && pre->next->next){ a=pre->next,b=pre->next->next; a->next=b->next;b->next=a;//b指向a,a指向b的下一个元素 pre->next=b;pre=a;//pre指向b,令pre为a } return res; } };