All problems

Remove Nth Node From End of List

Medium · linked list

You are given the head of a singly linked list and an integer n. Remove the nth node from the end of the list and return the head of the resulting list.

Counting starts at 1, so n = 1 is the last node and n = len(list) is the head. If you remove the only node, the answer is the empty list, so return None. The nodes you receive are ListNode objects with a val and a next.

Examples

Example 1

Input: head = [1, 2, 3, 4, 5], n = 2

Output: [1, 2, 3, 5]

The 2nd node from the end is 4, so it is removed and 3 now points at 5.

Example 2

Input: head = [1], n = 1

Output: []

The only node is also the last node. Removing it leaves an empty list.

Example 3

Input: head = [1, 2], n = 1

Output: [1]

Constraints