leetcode: Swap Nodes in Pairs

http://oj.leetcode.com/problems/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.

思路

每次读两个节点插入新链表,因为是指针操作,不占用额外空间。最后需要把tail指针的next设为NULL。例如链表为p1->p2->p3->p4的情况,如果最后不修改p3->next,那么就会出现一个环:p2->p1->p4->p3->p4->...

 1 class Solution {
 2 public:
 3     void insertTwoNodes(ListNode *p1, ListNode *p2, ListNode *&head, ListNode *&tail) {
 4         if (NULL == head) {
 5             head = tail = p2;
 6         }
 7         else {
 8             if (p2 != NULL) {
 9                 tail->next = p2;
10                 tail = p2;
11             }
12         }
13         
14         if (NULL == head) {
15             head = tail = p1;
16         }
17         else {
18             tail->next = p1;
19             tail = p1;
20         }
21     }
22     
23     ListNode *swapPairs(ListNode *head) {
24         ListNode *swapped_head = NULL, *swapped_tail = NULL;
25         
26         while (head != NULL) {
27             ListNode *p1 = NULL, *p2 = NULL;
28             
29             p1 = head;
30             head = head->next;
31             
32             if (head != NULL) {
33                 p2 = head;
34                 head = head->next;
35             }
36             
37             insertTwoNodes(p1, p2, swapped_head, swapped_tail);
38         }
39         
40         if (NULL != swapped_tail) {
41             swapped_tail->next = NULL;
42         }
43         
44         return swapped_head;
45     }
46 };

 

posted @ 2013-10-28 22:34  移山测试工作室黑灯老师  阅读(880)  评论(0编辑  收藏  举报
count website visits
Buy Computers