Remove the Nth Node From the End of a List
Remove the node that sits n positions from the end of a singly-linked list, then return the list.
Given the head of a singly-linked list and an integer n, remove the nth node from the end of the list and return its head.
Counting from the end is 1-indexed: the 1st node from the end is the last node, the 2nd node from the end is the second-to-last node, and so on.
You are guaranteed that n is always a valid position for the given list.
Example 1
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]
Example 2
Input: head = [1], n = 1
Output: []
Explanation: The only node is also the 1st from the end, so removing it leaves an empty list.
Example 3
Input: head = [1,2], n = 2
Output: [2]
Explanation: n equals the list's length, so the head itself is removed.
Constraints
- The number of nodes in the list is in the range [1, 30].
- 0 <= Node.val <= 100
- 1 <= n <= size of the list
Follow-up
Can you do this in a single pass through the list?
Hints
Companies
No companies reported yet.
Discussion
Sign in to join the discussion.
Loading discussion...
Test results
No test cases yet.