简繁EN

LeetCodeNo. 086

[LeetCode with Python] 19. Remove Nth Node From End of List

Contents

Problem

Problem page: https://leetcode.com/problems/remove-nth-node-from-end-of-list/
Topics: Linked List, Two Pointers
Difficulty: 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.


Analysis

Problems like this commonly use fast and slow pointers. The fast pointer stays n steps ahead of the slow one, so when it reaches the end, the other points to the node just before the one we need to remove.
The node to delete might be head itself. It's easier to add a "dummy head" than to handle that case separately. The same trick is common in similar linked list problems.


Code

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

Article link: https://xnerv.wang/en/leetcode-remove-nth-node-from-end-of-list/