Swap Nodes in Pairs Medium
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.
public ListNode swapPairs(ListNode head) {
ListNode p = head;
if (p == null || p.next == null)
return head;
ListNode newHead = p.next;
p.next = p.next.next;
newHead.next = p;
p = newHead.next.next;
newHead.next.next = swapPairs(p);
return newHead;
}
思路:递归,每次Swap两个,然后指向下一部分,最终返回当前部分的头给上一部分的尾。