Remove Nth Node From End of List
Given the head of a singly linked list and an integer n, remove the n-th node counting from the **end** of the list and return the head of the resulting list.
n is 1-indexed from the end: n = 1 removes the last node, n = 2 removes the second-to-last, and so on. n is always a valid position, so 1 <= n <= length. If the list had a single node, removing it leaves the empty list.
Lists are shown in array notation for readability — [1, 2, 3, 4, 5] is the chain 1 -> 2 -> 3 -> 4 -> 5, and the empty list is [].
Example cases
- remove 2nd from endin head = [1,2,3,4,5]12345nulln = 2out [1,2,3,5]1235nullCounting from the end, the 2nd node is `4`; removing it leaves `1 -> 2 -> 3 -> 5`.
- single nodein head = [1]1nulln = 1out []nullThe only node is the 1st from the end; removing it leaves the empty list.
- remove the headin head = [1,2]12nulln = 2out [2]2nullWith 2 nodes, the 2nd from the end is the head `1`.
Constraints
- The number of nodes in the list is in the range [1, 30].
- 0 <= Node.val <= 100
- 1 <= n <= the number of nodes in the list.
head =
[1,2,3,4,5]
n =
2