Google+ Followers

Monday, January 7, 2013

[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.
» Solve this problem

[解题思路]
双指针互换,要考虑一些边界条件,比如链表为空,链表长度为1,链表长度为2.
加一个safeGuard可以避开链表长度为2的检测。

[Code]
1:  ListNode *swapPairs(ListNode *head) {   
2:       if(head == NULL) return NULL;   
3:       if(head->next == NULL) return head;   
4:       ListNode* safeG = new ListNode(-1);   
5:       safeG->next= head; // head will be changed in next switch  
6:       ListNode *pre = head->next;   
7:       ListNode *cur = head;   
8:       ListNode *post = safeG;   
9:       while(pre!=NULL)   
10:       {   
11:            ListNode* temp = pre->next;   
12:            pre->next = cur;   
13:            cur->next = temp;   
14:            post->next = pre;   
15:            post= cur;   
16:            if(post->next == NULL) break;   
17:            cur = post->next;   
18:            pre = cur->next;           
19:       }   
20:       head = safeG->next;   
21:       delete safeG;   
22:       return head;   
23:  }   

Haoran给了一个递归解法,更简洁
1:    ListNode *swapPairs(ListNode *head) {  
2:      if (head == NULL || head->next == NULL) {  
3:        return head;  
4:      }  
5:      ListNode* nextPair = head->next->next;  
6:      ListNode* newHead = head->next;  
7:      head->next->next = head;  
8:      head->next = swapPairs(nextPair);  
9:      return newHead;  
10:    }  


Post a Comment