Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
29 lines (25 sloc) 732 Bytes
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.
ListNode *swapPairs(ListNode *head)
ListNode **newHead = &head;
ListNode *pNode1 = *newHead;
if(pNode1 == NULL)
return head;
ListNode *pNode2 = pNode1->next;
if(pNode2 == NULL)
return head;
*newHead = pNode2;
pNode1->next = pNode2->next;
pNode2->next = pNode1;
newHead = &(pNode1->next);
return head;