1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution 10 { 11 public: 12 ListNode* swapPairs(ListNode* head) 13 { 14 ListNode *left,*right,*cur; 15 ListNode *res=new ListNode(0); 16 left=res; 17 res->next=head; 18 cur=head; 19 while(cur!=NULL&&cur->next!=NULL) 20 { 21 ListNode *p=cur->next; 22 right=p->next; 23 p->next=cur; 24 left->next=p; 25 left=cur; 26 left->next=right; //very improtant,if we not do this,there will a two-node-circle and output will time exceed 27 cur=right; 28 } 29 return res->next; 30 } 31 };
一对一对地交换,left指向前面节点的末尾,cur指向当前节点对的第一个节点,right指向后续节点对的第一个节点。
值得注意的是,left更新后,left的next域要更新为right,不然left那里有个两节点的环,输出会超时。
原文:https://www.cnblogs.com/zhuangbijingdeboke/p/9273631.html