本文完整拆解 LeetCode 19 Remove Nth Node From End of List 的解法:從解題思路、演算法步驟到時間與空間複雜度,並整理邊界情況與 3 種解法比較,幫你把 Remove Nth Node From End of List 一次弄懂。
Explore diverse LeetCode solutions in Python, C++, JavaScript, SQL, and TypeScript. Ideal for interview prep, learning, and code practice in multiple programming languages. Github Repo Link
Medium
Given the head of a linked list, remove the nth node from the end of the list and return its head.
Example 1:
Input: head = [1,2,3,4,5], n = 2 Output: [1,2,3,5]
Example 2:
Input: head = [1], n = 1 Output: []
Example 3:
Input: head = [1,2], n = 1 Output: [1]
Constraints:
- The number of nodes in the list is
sz. 1 <= sz <= 300 <= Node.val <= 1001 <= n <= sz
Follow up: Could you do this in one pass?
內容目錄
TogglePython
# time complexity: O(n)
# space complexity: O(1)
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
total = 0
countNode = resNode = head
while countNode:
total += 1
countNode = countNode.next
delIdx = total - n - 1
if delIdx < 0:
head = head.next
return head
currentIdx = 0
while resNode:
if currentIdx == delIdx:
if resNode.next.next:
resNode.next = resNode.next.next
else:
resNode.next = None
return head
else:
resNode = resNode.next
currentIdx += 1
return head
root = ListNode(1)
root.next = ListNode(2)
root.next.next = ListNode(3)
root.next.next.next = ListNode(4)
root.next.next.next.next = ListNode(5)
print(Solution().removeNthFromEnd(root, 2))
Remove Nth Node From End of List 解題思路
單向串列沒辦法倒著走,但可以用「快慢指針拉開固定距離」來定位倒數第 n 個節點:讓快指針先走 n+1 步,之後兩個指針同步前進,當快指針走到結尾時,慢指針剛好停在要刪除節點的前一個。配合 dummy 節點,連「刪除頭節點」這個特例都能一併消掉。
Remove Nth Node From End of List 演算法步驟
- 建立 dummy 節點指向 head,fast 與 slow 都指向 dummy。
- 讓 fast 先往前走 n+1 步。
- fast 與 slow 同步前進,直到 fast 變成 null。
- 此時 slow.next 就是要刪除的節點,執行 slow.next = slow.next.next,回傳 dummy.next。
Remove Nth Node From End of List 複雜度分析
| 項目 | 複雜度 |
|---|---|
| 時間複雜度 | O(L) |
| 空間複雜度 | O(1) |
兩個指針合計走訪串列一次,時間為 O(L),只需一趟掃描。只用幾個指標變數,空間 O(1)——這優於「先算長度再走一次」的兩趟解法。
Remove Nth Node From End of List 的邊界情況與常見錯誤
- 使用 dummy 節點可以免去「刪除的是頭節點」的特判。
- fast 要先走 n+1 步而不是 n 步,差一就會刪錯節點。
- 題目保證 n 有效,否則要檢查 fast 是否提前變成 null。
- 刪除後原節點若需釋放,依語言決定是否手動處理。
Remove Nth Node From End of List 其他解法比較
| 解法 | 時間 | 空間 | 說明 |
|---|---|---|---|
| 先走一遍算長度再走第二遍 | O(L) | O(1) | 需要兩趟,邏輯較直覺 |
| 把節點全存進陣列後定位 | O(L) | O(L) | 多花一份空間 |
| 快慢指針一趟搞定 | O(L) | O(1) | 本文採用 |

