18/39
Part 4 of 7 · Cycles and meeting pointsLearn and do
On a short loop, the pointer from the meeting point goes round whole laps first
A common shortcut says the meeting point is nodes short of the loop's start. The start can be closer than that, and then the pointer from the meeting point makes whole laps while the other one walks in. Try a long lead-in and a short loop, nodes 0 to 8 with node 8 pointing back at node 6, so and :
def both_phases(head):
slow = fast = head
i = 0
while True:
slow, fast = slow.next, fast.next.next
i += 1
if slow is fast:
break
node, meet, steps = head, slow, 0
while node is not meet:
node, meet = node.next, meet.next
steps += 1
print(f"meet on node {slow.val} after i = {i} steps")
print(f"then both on node {node.val} after {steps} more steps")
both_phases(looped(9, 6))
looped(9, 6): a lead-in of 6 nodes and a loop of 3. Where do slow and fast meet?
Pick one to see what it prints.
Pick an answer above to see the rest