Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
29 lines (25 sloc) 732 Bytes
problem:
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.
------------------------------------------------------------------------------------------
solution:
ListNode *swapPairs(ListNode *head)
{
ListNode **newHead = &head;
while(1)
{
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;
}