Skip to content

Instantly share code, notes, and snippets.

@zhoutuo
Created February 14, 2013 18:43
Show Gist options
  • Save zhoutuo/4955164 to your computer and use it in GitHub Desktop.
Save zhoutuo/4955164 to your computer and use it in GitHub Desktop.
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.
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode tmpHead(-1);
tmpHead.next = head;
ListNode* pre = NULL;
ListNode* post = &tmpHead;
ListNode* result = NULL;
if(head != NULL && head->next != NULL) {
result = head->next;
} else {
result = head;
}
while(true) {
pre = post;
if(post->next != NULL) {
post= post->next;
} else {
break;
}
if(post->next != NULL) {
post= post->next;
} else {
break;
}
ListNode* first = pre->next;
ListNode* second = first->next;
ListNode* tmp = second->next;
second->next = first;
pre->next = second;
first->next = tmp;
post = post->next;
}
return result;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment