首页 > 其他 > 详细

[LeetCode]Swap Nodes in Pairs

时间:2015-11-01 19:12:05      阅读:340      评论:0      收藏:0      [点我收藏+]

题目描述:(链接

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.

 

Subscribe to see which companies asked this question

解题思路:
 1 class Solution {
 2 public:
 3     ListNode *swapPairs(ListNode *head) {
 4         if (!head || !(head->next)) {
 5             return head;
 6         }
 7         
 8         ListNode dummy(-1);
 9         dummy.next = head;
10         ListNode *prev = &dummy;
11         ListNode *cur = prev->next;
12         ListNode *next = cur->next;
13         
14         while (next != nullptr) {
15             prev->next = next;
16             cur->next = next->next;
17             next->next = cur;
18             
19             prev = cur;
20             cur = cur->next;
21             next = cur? cur->next : nullptr;
22         }
23         return dummy.next;
24     }
25 };

 

[LeetCode]Swap Nodes in Pairs

原文:http://www.cnblogs.com/skycore/p/4928334.html

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