Example 1
- Input
- head = [1,2,3,4,5], n = 2
- Output
- [1,2,3,5]
The 2nd node from the end holds 4, so removing it leaves [1,2,3,5].
Given the head of a singly linked list and an integer n, remove the nth node from the end of the list in a single pass and return the head of the modified list.
Given the head of a singly linked list, remove the nth node from the end of the list and return the head of the modified list.
The position n is always valid, and the follow-up asks for a single-pass solution.
Reuse the surviving nodes in their original order and change only the link needed to bypass the target. The removed node need not have its own next link cleared; it simply must be unreachable from the returned head.
sz.1 <= sz <= 300 <= Node.val <= 1001 <= n <= szThe 2nd node from the end holds 4, so removing it leaves [1,2,3,5].
Removing the only node leaves an empty list.
The 1st node from the end holds 2, so removing it leaves [1].
The 3rd node from the end is the original head even though all values are equal. Return the original second node, retaining the other two nodes in order; values alone cannot identify which node was removed.
A singly linked list cannot walk backward, so locate the target's predecessor using information gathered while moving forward. If the length is L, the target has one-based position L - n + 1; in Example 1 that is position 4, holding value 4. Either measure L first, or keep a leader n + 1 links ahead of a trailer so the leader reaching null places the trailer immediately before the target. A dummy predecessor makes removing the head work like any other deletion.
Reveal Two Passes: intuition, complexity, and code
n equals the length): left never leaves dummy, so the bypass still works.n = 1: the bypass empties the list and dummy.next is null.n = 1) changes its predecessor.next to null; no surviving node should still reach the tail.A dummy node absorbs deletions at the head, and a fixed gap between two pointers converts distance-from-the-end into a one-pass location.