码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Swap Nodes in Pairs

时间:2015-11-01 19:13:14      阅读:124      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!