LeetCode OJ:Swap Nodes in Pairs(成对交换节点)

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.

如题实例所示,需要成对的交换节点,这里我用到了两个帮助节点,一个记下起点的前面位置,一个作为每一对prev的前面一个节点使用,思路比较简单,就是交换之后再向后面移动两个节点就可以了,代码如下所示:

 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 public:
11     ListNode* swapPairs(ListNode* head) {
12         if(!head) return NULL;
13         if(!head->next) return head;
14           ListNode * helper1 = new ListNode(INT_MIN);
15           ListNode * helper2 = new ListNode(INT_MIN);
16           helper1->next = head;
17           helper2->next = head->next;// 先记录下首节点的位置,供函数返回的时候使用
18           ListNode * prev = head;
19           ListNode * curr = head->next;
20           while(prev){
21               if(curr){
22                   ListNode * tmpNode = curr->next;
23                   curr->next = prev;
24                   helper1->next = curr;
25                   prev->next = tmpNode;
26                   helper1 = prev;
27                   if(prev->next && prev->next->next){
28                       prev = prev->next;
29                       curr = prev->next;
30                   }else
31                       break;
32               }else
33                   break;
34               
35           }      
36           return helper2->next;
37     }
38 };

 

posted @ 2015-12-30 14:50  eversliver  阅读(230)  评论(0编辑  收藏  举报