這一題困難的點在於,因為題目給的 Linked List 沒有紀錄現在的長度,所以你很難直接算出到底哪個點是倒數第N個點.
https://leetcode.com/problems/remove-nth-node-from-end-of-list/
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]
slow 指標比 fast 指標慢 n+1 個節點.
則當 fast 指標到達最後一個節點時, slow 指標剛好落在倒數第n個節點的前一個節點.
這時我們只要處理 slow 指標,把 slow 指標的下一個節點指向下下個節點即是答案.
Python
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
fast = head
slow = ListNode(-1, head)
for _ in range(n):
fast = fast.next
while fast != None:
fast = fast.next
slow = slow.next
if slow.next == head:
return head.next
slow.next= slow.next.next
return head
Go
func removeNthFromEnd(head *ListNode, n int) *ListNode {
fast := head
slow := &ListNode{0, head}
// move fast only
for i := 0; i < n ; i++ {
fast = fast.Next
}
// move together
for fast != nil {
fast = fast.Next
slow = slow.Next
}
//remove the nth
if slow.Next == head {
return head.Next
}
slow.Next= slow.Next.Next
return head
}