[LeetCode] 115: Swap Nodes in Pairs

来源:互联网 发布:mac图片文件夹在哪里 编辑:程序博客网 时间:2024/06/05 11:17
[Problem]

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.


[Solution]
/**
* 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) {
// Note: The Solution object is instantiated only once and is reused by each test case.

// short than two nodes
if(NULL == head || NULL == head->next)return head;

// variables definition
ListNode *p1 = head;// the first node
ListNode *p2 = head->next;// the second node
ListNode *pre = p1;// the node before p1
ListNode *after = p2->next;// the node after p2;

// swap
while(p2 != NULL){
// the first pair
if(pre == p1){
head = p2;
}
else{
pre->next = p2;
}
p2->next = p1;
p1->next = after;

// update p1, p2, pre, after
pre = p1;
p1 = pre->next;
if(p1 == NULL)break;
p2 = p1->next;
if(p2 == NULL)break;
after = p2->next;
}
return head;
}
};
说明:版权所有,转载请注明出处。Coder007的博客