Remove the Nth Node from the End
Problem statement
Given the head of a singly linked list and an integer n, remove the nth node from the end and return the resulting head.
Count from the end starting at 1: n = 1 removes the tail. The input is nonempty and acyclic, and n is valid for its length.
Reuse the remaining nodes and preserve their order. Exactly one node is removed even when values repeat. Removing the only node returns an empty list. Lists are displayed as arrays of node values.
Function
removeNthFromEnd(head: ListNode, n: int) → ListNodeExamples
Example 1
head = [4,7,2,9,6]n = 2return = [4,7,2,6]From the end, 6 is first and 9 is second, so the node with value 9 is removed.
Example 2
head = [8]n = 1return = []The only node is also the first from the end. The resulting head is null.
Constraints
- The list length
Lsatisfies1 <= L <= 1000. 1 <= n <= L.- Each node value is an integer in
[-10^6, 10^6]. - The list contains no cycle.