Swap Nodes in Pairs

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.

01 ListNode *swapPairs(ListNode *head) {
02         if(head==NULL)
03             return NULL;
04         if(head->next==NULL)
05             return head;
06         ListNode* hd=head->next;
07         ListNode* tmp=hd->next;
08         hd->next=head;
09         head->next=swapPairs(tmp);
10         return hd;
11 }
This entry was posted in Array and linked list, Recursive. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s