1. 程式人生 > >LC_24. Swap Nodes in Pairs

LC_24. Swap Nodes in Pairs

log des desc pop link ppa script rip lis

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

LC_24. Swap Nodes in Pairs