[LeetCode] 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.

利用三个指针p, pPre, pPrePre来操作,画个图就比较清晰了

 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         // Start typing your C/C++ solution below
13         // DO NOT write int main() function
14         if (head == NULL)
15             return NULL;
16             
17         ListNode *pPrePre = NULL;
18         ListNode *pPre = NULL;
19         ListNode *p = head;
20         
21         while(p && p->next)
22         {
23             pPre = p;
24             p = p->next;
25             
26             ListNode *pNext = p->next;
27             
28             if (pPre == head)
29                 head = p;
30                 
31             if (pPrePre)
32                 pPrePre->next = p;
33                 
34             p->next = pPre;
35             pPre->next = pNext;
36             
37             pPrePre = pPre;
38             p = pNext;
39         }
40         
41         return head;
42     }
43 };
posted @ 2012-11-19 17:07  chkkch  阅读(3258)  评论(0编辑  收藏  举报