LeetCode19 Remove Nth Node From End of List
Author: Stefan Su
Create time: 2022-10-29 00:28:17
Location: New York City, NY, USA
Description 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]
Constrains
- The number of nodes in the list is
sz
. 1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
Analysis
We use two pointers to solve this problem. The fast pointer moves first, the range is n+1
. And then, slow and fast pointers move together until fast pointer is None
. At this time, slow pointer is at the previous node of that node which should be removed. Use slow.next = slow.next.next
to remove the node. The most important thought in this problem is move fast pointer n+1
steps.
Solution
- Two pointers version
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
dummy_head = ListNode(0)
dummy_head.next = head
fast = slow = dummy_head
for _ in range(n + 1): # key condition
fast = fast.next
while fast != None:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy_head.next
Hopefully, this blog can inspire you when solving LeetCode19. For any questions, please comment below.