Visualize the algorithm to remove the n-th node from the end of a linked list in two passes: count, then unlink.
About this algorithm
Given a singly linked list and a number n, remove the node that sits n places from the end, so n = 1 removes the tail. The difficulty is that a singly linked list can only be walked forward, so there is no way to count back from the end directly.
This is a pattern as much as a problem: any time you need a position measured from the end of a forward-only list, either count the length first or keep two pointers a fixed gap apart. The two-pass count, which this page shows, is the easiest to get right. The one-pass gap method suits a list you may only walk once, or an interviewer who asks for a single pass. For the middle node rather than a fixed distance from the end, use the fast and slow pointers on the Find Middle page.
Walk a pointer from the head to the end, counting nodes, to get the length L.
The node to remove is at index L - n, counting from 0. If that index is 0, the head itself goes: move head to head.next and you are done.
Walk a second pointer from the head L - n - 1 steps, to the node just before the one being removed. You need the node before, not the node itself, because its next pointer is the one that has to change.
Set before.next = before.next.next. The removed node can no longer be reached from the head.
The page loads 10, 20, 30, 40, 50, 60, 70 and uses n = 2 when the box is left empty. Pass 1 counts 7 nodes. The target index is 7 - 2 = 5, which holds 60, the second node from the end. Pass 2 moves the pointer 4 steps from 10 and stops on 50, at index 4. Setting 50.next to 70 removes 60, and the list becomes 10, 20, 30, 40, 50, 70. Try n = 7: the index is 0, so the head, 10, is removed without a second pass.
Put a dummy node in front of the head and start two pointers on it. Move the lead pointer n + 1 steps ahead, then move both together until the lead falls off the end. The trailing pointer now sits just before the node to remove. The dummy node means removing the head needs no special case.
Time: two walks of at most L nodes each, so O(L); the one-pass version does the same amount of work in a single walk. Space: a counter and two pointers, so O(1).