Where it runs
1. The problem
Delete the 2nd node from the end of a list. On an array that is one line: arr.splice(arr.length - 2, 1). The array knows its length. A linked list is built differently: it is a chain of nodes, and each node knows only the next one. You can walk it only forward, and you don't know its length in advance. So counting "from the end" is awkward.
The simple fix takes two passes. The first pass counts the nodes. The second walks to position length - n. In this lesson you do the same in one pass. Two pointers help again, as when you found the middle of a list. This time they move at the same speed and keep a fixed distance between them.
This step is part of the paid track
The first 33 steps are open to everyone: lesson, exercise and tests. This one opens with full access. Start with a free account and the free steps.
Create a free accountSee what is includedOn LeetCode
Linked list problems that count from the end of the list, or need two spots a known distance apart. Move one pointer n steps ahead, then walk both until the front one runs out.
The lesson task, with a dummy node so that removing the head needs no special case.
Find the kth node from the front, then use the same gap of k to find the kth from the end, and swap their values.
Count the length, reduce k modulo it, then the new tail is the node k from the end.
Give the longer list a head start equal to the difference in lengths, then walk both until they land on the same node.