標籤:
題目在這裡: https://leetcode.com/problems/remove-nth-node-from-end-of-list/
【標籤】 Linked List; Two Pointers
【個人分析】
這個題目應該算是Linked List裡面的基礎題。說它基礎不是因為它簡單,而是因為它是基石。一些 Linked list中經典方法在這道題裡面都有應用。
1. Two Pointers 在 Linked List中: 如果能預先鏈表知道長度,那題目就簡單多了,刪掉從頭開始的 Len - N就完事了。但是,LinkedList是沒有辦法預Crowdsourced Security Testing道鏈表長度的,所以需要藉助雙指標來利用offset來解決。
1.1)設定兩個指標,fast 和 slow。
1.2) 讓fast先單獨走 n 步(這樣,fast 和 slow這件就有了固定的差距:n)。
1.3) 然後兩個指標一起往前走,當 fast.next = null, 即 fast是鏈表中最後一個結點時,slow就指在倒數第 n + 1個結點處, 也就是我們想要刪除的那個結點前面的那個結點。
1.4) 讓slow.next = slow.next.next,這樣就成功刪除掉了原先的slow.next
2. dummy head的應用: dummy head 就是我們自己建立一個結點,然後讓原先的head結點接到這個建立結點的後面。我覺得用dummy head用三個比較明顯的好處。
一個是可以盡量減少對原先鏈表的改變,如果是用head = head.next這樣的方法,head會移動,這樣就改變了原先的情況,不是很好。
二個好處是方便返回,直接返回dummy.next就可以。
三個是不用對頭結點做特除對待,如果刪除的結點恰好是頭結點,還要為這種情況單獨寫一些代碼,增加了代碼量。
總之,如果要求返回新的頭結點的鏈表題目,建立一個dummy head多半是比較好的選擇。
1 public class Solution { 2 public ListNode removeNthFromEnd(ListNode head, int n) { 3 if (head == null || n <= 0) { 4 return null; 5 } 6 ListNode dummyHead = new ListNode(-1); 7 dummyHead.next = head; 8 9 ListNode fast = dummyHead;10 ListNode slow = dummyHead;11 12 // let fast point go n steps itself13 for (int i = 0; i < n; i++) {14 assert(fast != null);15 fast = fast.next;16 }17 18 // fast and slow go together 19 // until fast reaches the end of list20 while (fast.next != null) {21 fast = fast.next;22 slow = slow.next;23 }24 25 // now slow should pointing to the node 26 // before which we want to remove27 slow.next = slow.next.next;28 29 return dummyHead.next;30 }31 }
[Leetcode][019] Remove Nth Node From End of List (Java)