LC_24. Swap Nodes in Pairs
阿新 • • 發佈:2018-02-21
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->49 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