Remove Nth Node From End of List
MediumLinked List
You are given head, the first node of a singly linked list, and an integer n. Remove the n-th node counting from the end of the list (n = 1 is the last node) and return the head of the resulting list.
If the removed node is the head, return the node that followed it (or None if the list becomes empty). n is always between 1 and the length of the list.
Follow-up: can you do it in a single pass?
Example 1
- Input:
- head = [1,2,3], n = 3
- Output:
- [2,3]
- Explanation
- Counting from the end, node 1 is
3, node 2 is2and node 3 is1. The node removed is the head, so the returned list starts at 2.
Example 2
- Input:
- head = [4,9,6], n = 1
- Output:
- [4,9]
- Explanation
n = 1means the last node, so 6 is dropped and 9 becomes the new tail.
Example 3
- Input:
- head = [7,7,8,7], n = 3
- Output:
- [7,8,7]
- Explanation
- The 3rd node from the end is the 2nd node (a
7). Values repeat, so it is the position, not the value, that identifies which node to remove.
Constraints
- The number of nodes
szis in the range[1, 30] 0 <= Node.val <= 1001 <= n <= sz