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.
SOLUTION 1:
递归解法:
1. 先翻转后面的链表,得到新的Next.
2. 翻转当前的2个节点。
3. 返回新的头部。
1 // Solution 1: the recursion version. 2 public ListNode swapPairs1(ListNode head) { 3 if (head == null) { 4 return null; 5 } 6 7 return rec(head); 8 } 9 10 public ListNode rec(ListNode head) { 11 if (head == null || head.next == null) { 12 return head; 13 } 14 15 ListNode next = head.next.next; 16 17 // 翻转后面的链表 18 next = rec(next); 19 20 // store the new head. 21 ListNode tmp = head.next; 22 23 // reverse the two nodes. 24 head.next = next; 25 tmp.next = head; 26 27 return tmp; 28 }