1. 程式人生 > >領釦(LeetCode)刪除連結串列的倒數第N個節點 個人題解

領釦(LeetCode)刪除連結串列的倒數第N個節點 個人題解

給定一個連結串列,刪除連結串列的倒數第 個節點,並且返回連結串列的頭結點。

示例:

給定一個連結串列: 1->2->3->4->5, 和 n = 2.

當刪除了倒數第二個節點後,連結串列變為 1->2->3->5.

說明:

給定的 n 保證是有效的。

進階:

你能嘗試使用一趟掃描實現嗎?

 

快慢針的思想。快針先移動N個步長,然後兩個針一起移動,快針結束時,慢針指向倒數第N+1個節點。然後就是簡單的刪除節點操作了。這裡需要注意刪除的節點是第一個節點的特判。

這裡由於使用了JAVA,對返回head突然有了新的疑惑,為什麼操作fast和slow會影響到head的內容。這裡需要認真學習一下。

程式碼如下:

 1 class Solution {
 2     public ListNode removeNthFromEnd(ListNode head, int n) {
 3         if (head == null)
 4             return null;
 5         ListNode slow = head;
 6         ListNode fast = head;
 7         while (n >= 1 && fast.next != null) {
 8             fast = fast.next;
9 n--; 10 } 11 if (n > 1) 12 return head; 13 if (n == 1) 14 return head.next; 15 while (fast.next != null) { 16 slow = slow.next; 17 fast = fast.next; 18 } 19 slow.next = slow.next.next; 20 return
head; 21 } 22 }