Use a fixed pointer gap to remove a linked-list node in one pass.
Remove the nth node counted from the end. When n = 1, remove the tail. Return the head of the remaining list.
Find the node without measuring the list first
The removed node may be the head, the tail, or the only node.
Submit your implementation when it passes the examples.
Given the head of a singly linked list and an integer n, remove the nth node counted from the end.
Return the list's head after the removal. Each node has the shape { val, next }.
1 ≤ n ≤ number of nodes ≤ 30Results appear here after a run.
Start slow at a dummy node just before the head and fast at the head. Advance fast by n links, then move both pointers together until fast reaches null. Throughout the paired walk, fast is n links ahead of slow.next.
In the diagram, n = 2. From node 50 it takes two links to reach null, through 60. When fast reaches null, slow points to 40, so link 40 directly to 60. If n equals the entire list length, slow stays at the dummy and the same update removes the head.
function removeNthFromEnd(head, n) {
const dummy = { val: 0, next: head };
let fast = head;
let slow = dummy;
for (let step = 0; step < n; step++) {
fast = fast.next;
}
while (fast !== null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dummy.next;
}| Measure | Complexity | Explanation |
|---|---|---|
| Time | O(L) | For a list of length L, each pointer advances at most L times. The input n specifies the position counted from the end. |
| Auxiliary space | O(1) | The algorithm uses one dummy node and two pointers. |