您的位置:首页 > Web前端 > Node.js

24. Swap Nodes in Pairs

2016-03-28 00:08 661 查看
1.Question

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.

2.Code

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head == NULL || head->next == NULL)
return head;
ListNode *p1 = head, *p2 = head->next, *p3;
head = head->next;
while(p2)
{
p1->next = p2->next;
p2->next = p1;
if(head != p2)
p3->next = p2;
p3 = p1;
p1 = p1->next;
if(p1)
p2 = p1->next;
else
p2 = NULL;
}
return head;
}
};


3.Note
a. 这个题两个数一组处理就好了,例如:abc的顺序,则先让a指向c, b指向a。然后进入到下一组的两个数。还有就是要更新上一组的数字指向当前组交换后的数字,以及第一次交换的特殊处理。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: