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.

分析:两两为一组进行交换。链表要注意的就是 进行新的赋值操作之后,原来的地址能不能被访问。

   nN  move

比如:1->2->3->4->5->6

命名1为nN,2为move,如果1的next指向3,那么2仍然可以以move的名义被访问,而不用是nN->next。但如果2的next指向4,那么3不能够被访问了,因为新的赋值已经将move->next指向4,原来的3会被覆盖,所以move->next指向的是4而不是3。

运行时间:4ms

 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 || !head->next) return head;
13         
14         ListNode* newList = new ListNode(0);
15         newList->next = head;
16         ListNode* pre = newList;
17         ListNode* move = head;
18         while(move && move->next){
19             newList->next = move->next;
20             newList = newList->next;
21             move->next = move->next->next;
22             newList->next = move;
23             newList = newList->next;
24             move = move->next;
25         }
26         if(move) newList->next = move;
27             
28         return pre->next;
29     }
30 };

 

posted @ 2015-05-20 00:46  amazingzoe  阅读(205)  评论(0编辑  收藏  举报