首页 > 其他 > 详细

24. Swap Nodes in Pairs

时间:2018-07-06 15:33:24      阅读:152      评论:0      收藏:0      [点我收藏+]
 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那里有个两节点的环,输出会超时。

24. Swap Nodes in Pairs

原文:https://www.cnblogs.com/zhuangbijingdeboke/p/9273631.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!