Created
July 4, 2013 17:50
-
-
Save barrysteyn/5929339 to your computer and use it in GitHub Desktop.
LeetCode: Swap pairs
This file contains hidden or 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
| /* | |
| * In a competition to see who would use the least pointers | |
| * for reversing nodes in a linked list, I think this solution | |
| * should be entered. There are easier solutions to read/spot, | |
| * but I think this is the most elegant. | |
| */ | |
| class Solution { | |
| public: | |
| ListNode *swapPairs(ListNode *head) { | |
| if (!head || !head->next) return head; | |
| ListNode newHead(0); | |
| newHead.next = head; | |
| ListNode *prev = &newHead; | |
| head=head->next; | |
| while (head) { | |
| prev->next->next = head->next; | |
| head->next = prev->next; | |
| prev->next = head; | |
| prev = head->next; | |
| head = (prev && prev->next) ? prev->next->next : NULL; | |
| } | |
| return newHead.next; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment