Date and Time: Jul 31, 2024, 17:53 (EST)
Link: 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]
-
The number of nodes in the list is
sz
. -
1 <= sz <= 30
-
0 <= Node.val <= 100
-
1 <= n <= sz
-
Set a dummy node
dummy = tail = ListNode(0, head)
and set right to ben
positions away fromhead
by using while loop to advanceright
. -
We move
tail
andright
together untilright
isNone
, so we knowtail.next
is thenode
we want to remove. And we just linktail.next = tail.next.next
to skip the node we need to remove.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
# Follow the hint, we use two pointers and the gap between them is n + 1, we can do that by creating a dummy node
dummy = tail = ListNode(0, head)
right = head
# We first advance the right pointer
while n > 0 and right:
right = right.next
n -= 1
while right:
tail, right = tail.next, right.next
tail.next = tail.next.next
return dummy.next
Time Complexity:
Space Complexity:
Language | Runtime | Memory |
---|---|---|
Python3 | ms | MB |
Java | ms | MB |
C++ | ms | MB |