Linked listsAnimated
Detect and Remove Loop
Find the cycle start with Floyd, then cut the last node.
Time
O(n)
Extra space
O(1)
Use it for
Repairing corrupted lists.
How it works
- Detect the cycle with slow and fast pointers, as in Floyd’s algorithm.
- When they meet, move one pointer back to the head and advance both one step at a time. They meet exactly at the node where the cycle begins.
- Walk around until you reach the node whose next is that start node: it is the last node in the loop.
- Set its next to empty to break the loop.
Watch it run
Loading animation…