https://leetcode.com/problems/swap-nodes-in-pairs/description/
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.
1 public ListNode swapPairs(ListNode head) { 2 //如果是最后一对的话,head.next.next 是可以为 NULL 的,所以不要进行判断 3 if (head == null || head.next == null) return head; 4 //base 5 ListNode newHead = swapPairs(head.next.next) ;//head is 1, newHead is 4 6 //currently head is 1, 4->3->null 7 ListNode tail = head.next ; //tail is 2 8 head.next = newHead ; //1->4 9 tail.next = head ; //2->1 10 return tail; 11 }
2-1-4-3-5
5 自己就弹了,所以没有后面的处理,所以(tail=3)tail.next 还是 直接连 last pop head(5) 所以是 2-1-4-3-5