題目
原題頁面:https://leetcode.com/problems/remove-nth-node-from-end-of-list/
題目型別:Linked List, Two Pointers
難度評價:Easy
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
分析
常見的快慢指標題目。快指標領先慢指標n步,這樣當快指標到達尾部時,慢指標正好指向需要刪除的節點的父結點。
注意由於要刪除的結點可能剛好是head節點,這種情況與其特殊處理,不如加一個“偽head”,這也是類似的連結串列類題目的通用做法。
程式碼
1 | class Solution: |
本文地址:https://xnerv.wang/zh-tw/leetcode-remove-nth-node-from-end-of-list/
