Skip to content

Instantly share code, notes, and snippets.

@barrysteyn
Created July 4, 2013 17:50
Show Gist options
  • Select an option

  • Save barrysteyn/5929339 to your computer and use it in GitHub Desktop.

Select an option

Save barrysteyn/5929339 to your computer and use it in GitHub Desktop.
LeetCode: Swap pairs
/*
* 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