Problem
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given
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.
Code
ListNode *swapPairs(ListNode *head) { // Note: The Solution object is instantiated only once and is reused by each test case. if(!head) return 0; ListNode *first = head; ListNode *second = head->next; if(!second) return first; ListNode *third = second->next; second->next = first; first->next = swapPairs(third); return second; }
No comments:
Post a Comment