首页 > 其他 > 详细

Swap Nodes in Pairs

时间:2015-06-14 21:13:41      阅读:220      评论:0      收藏:0      [点我收藏+]

Description:

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

Code:

 1   ListNode* swapPairs(ListNode* head) {
 2         if (!head)
 3             return NULL;
 4         ListNode *preNode = new ListNode(0);
 5         preNode ->next = head;
 6         
 7         ListNode *m_preNode = preNode;
 8         ListNode *p = head;
 9         ListNode *q = p->next;
10         
11         while (p&&q)
12         {
13             preNode->next = q;
14             p->next = q->next;
15             q->next = p;
16           
17             preNode = p;
18             p = preNode->next;
19             //要注意检测p是否为空值,否则对q赋值就会出现错误
20             if (p)
21                 q = p->next;
22             else
23                 q = NULL;
24         }
25       return m_preNode->next;
26     }

技术分享

Swap Nodes in Pairs

原文:http://www.cnblogs.com/happygirl-zjj/p/4575664.html

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