码迷,mamicode.com
首页 > 其他好文 > 详细

【Leetcode】【Medium】Swap Nodes in Pairs

时间:2015-05-19 07:08:25      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

解题思路:

传统的链表操作题,需要注意如果结点不是偶数,最后一个结点不需要交换,放在队尾。

代码1:

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

 

代码2,使用二维指针:

基本逻辑实现:

1 ListNode **p = &head;
2 while (*p && (*p)->next) {
3     // n表示待交换的两个结点中,后一个结点
4     ListNode* n = (*p)->next; 
5     (*p)->next = n->next; 
6     n->next = *p;
7     p = &(*p)->next;
8 }

由于二维指针p一直在操作当前需要交换的结点,不断向后迭代,而head指针此时指向的是链表中第二个结点(前两个交换);

因此上述代码唯一的问题是,没有指针指向头结点,无法返回...

所以我们希望在第一轮交换时,将head结点重新指向交换后的第一个结点。观察到第一轮交换时,*p其实就代表head,操作*p的指向,就是操作head的指向。

所以,最终代码为:

 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         ListNode **p = &head;
13 
14         while (*p && (*p)->next) {
15             ListNode* n = (*p)->next;
16             (*p)->next = n->next;
17             n->next = *p;
18             *p = n;
19             p = &(*p)->next->next;
20         }
21 
22         return head;
23     }
24 };

 

【Leetcode】【Medium】Swap Nodes in Pairs

标签:

原文地址:http://www.cnblogs.com/huxiao-tee/p/4513485.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!