Practice · Linked list · 6 of 6

Remove the Nth Node from the End

You are given head, the first node of a singly linked list, and a number n.

Remove the nth node counting from the end of the list (n = 1 is the last node), and return the head of what remains. If the list had only one node, what remains is empty. Try to do it in a single pass over the list.

Linked lists are written as their values from head to tail, so [1, 4, 6] is 1 → 4 → 6.

Example 1

Input
head = [10, 20, 30, 40, 50], n = 2
Output
[10, 20, 30, 50]
Counting from the end, 50 is first and 40 is second.

Example 2

Input
head = [7, 8], n = 2
Output
[8]
The second node from the end is the head itself, so 8 becomes the new head.

Constraints

  • The list holds 1 to 5000 nodes.
  • 1 ≤ n ≤ the number of nodes.
  • Every value is between −10⁴ and 10⁴.