24. Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.

Note:

  • Your algorithm should use only constant extra space.
  • You may not modify the values in the list's nodes, only nodes itself may be changed.

思考:假设有链表1->2->3->4->5->6。现在先交换3,4.变为1->2->4->3->5->6。这个过程中只需要知道节点2的地址,其他所有的信息就都知道了。

1、通过2访问到4,保存4中的指针于sec_tmp;

2、通过2访问3,并将其赋值给4的指针域;这样4就指向了3;

3、通过2访问3,并将3的指针域赋值为sec_tmp,这样3就指向了5;

4、将2的指针域赋值为2的地址。

5、这两个节点完成交换。

6、向下移动两步,到达3,进行新的一轮交换。

在这个过程的最后还要注意奇偶数,如果最后只剩一个,不需要处理。

 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         
13         
14         if(head==NULL || head->next==NULL) return head;
15         
16         //process the first and second nodes.
17         ListNode *new_head;
18         new_head = head->next;
19         ListNode *sec_tmp = head->next->next;
20         head->next->next = head;
21         head->next = sec_tmp;
22         
23         //process the remain nodes.
24         ListNode *p1,*p2;
25         p1 = new_head->next;
26         
27         while(p1->next!=NULL && p1->next->next!=NULL) {
28             p2 = p1->next->next;
29             sec_tmp = p2->next;
30             p2->next = p1->next;
31             p1->next->next = sec_tmp;
32             p1->next = p2;
33             
34             p1 = p1->next->next;
35         } 
36         
37         return new_head;
38         
39     }
40 };

猜你喜欢

转载自www.cnblogs.com/midhillzhou/p/8985185.html