Created
February 14, 2013 18:43
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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