简繁EN

LeetCodeNo. 086

【LeetCode with Python】 19. Remove Nth Node From End of List

目錄

題目

原題頁面: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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
# @return a ListNode
def removeNthFromEnd(self, head, n):
if None == head:
return head
if None == head.next:
return None
new_head = ListNode(-1)
new_head.next = head
fast = new_head
for i in range(0, n):
if None != fast.next:
fast = fast.next
else:
return head
slow = new_head
while None != fast.next:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return new_head.next

本文地址:https://xnerv.wang/zh-tw/leetcode-remove-nth-node-from-end-of-list/