Part 3 of 7 · Reversing and two speedsLearn and do
Keep a gap of k, and the trailing pointer stops k from the end
A fixed gap between two pointers finds a position counted from the end.
def kth_from_end(head, k): lead = head for _ in range(k): if lead is None: # fewer than k nodes return None lead = lead.next trail = head while lead is not None: lead, trail = lead.next, trail.next return trailnums = linked([1, 2, 3, 4, 5])print([kth_from_end(nums, k).val for k in (1, 2, 5)], kth_from_end(nums, 6))
Predict
On 1 to 5, what are the 1st, 2nd and 5th from the end, and the 6th?
Pick one to see what it prints.
lead goes k nodes ahead first. Then both move one node at a time until lead falls off the end. The gap stays k, so trail stops k from the end. Here k is 2, t is trail and l is lead:
k = 2: t is trail and l is lead
walk
12345Nonestarttlstep 1tlstep 2tlstep 3tl
lead is None after step 3, and trail stops on the 4, 2 from the end.
The question usually asks for one pass. Counting the length first and then walking n - k nodes follows next exactly as many times. So if you're asked why the gap version is better, the honest answer is that it's one loop, not fewer steps.
In the editor, write remove_kth_from_end(head, k) in one pass, with a dummy head. It removes the 2nd from the end of five nodes, then the 3rd from the end of three.
Pick an answer above to see the rest
Instructions
1
Write remove_kth_from_end(head, k): remove the k-th node from the end, for k from 1 to the length, and return the head.
2
Keep a gap of k between two pointers, and start both at a dummy head so removing the first node needs no special case.