Visualize a circular linked list where the tail points back to an earlier node. Build, break, and detect cycles with Floyd’s algorithm.
About this algorithm
In a circular linked list the last node's next pointer leads back to an earlier node instead of to null, so the list has no end. This page builds a singly linked circular list and uses Floyd's tortoise and hare method to prove the loop is there: a slow pointer and a fast pointer chase each other round the ring until they land on the same node.
Use a circular list when the data really is a loop: players taking turns in a game, a round-robin scheduler that hands time to each job in order, a playlist on repeat. Keeping a pointer to the tail gives O(1) access to both ends, since tail.next is the head. Use a plain singly or doubly linked list when the data has a clear end. The cycle check shown here matters for any linked list: a list you expect to end at null but that loops by mistake makes a simple while (node) loop run forever.
When the list is built, the tail's next pointer is set to the head. Appending, prepending or deleting the head re-links the tail so the ring stays closed. You can also point the tail at any index, or break the ring, to set up other cases.
Slow and fast both begin on the head node.
Each round, if fast or fast.next is null, the list has an end and there is no cycle. Otherwise move slow one node forward and fast two nodes forward.
Once both are inside the loop, fast gains one node on slow every round, so the gap between them shrinks by one each time and must reach zero. When slow and fast land on the same node, a cycle exists.
The page loads 10, 20, 30, 40, 50, 60, 70 with 70 pointing back to 10. Both pointers start on 10. Round 1: slow 20, fast 30. Round 2: slow 30, fast 50. Round 3: slow 40, fast 70. Round 4: slow 50, and fast wraps round to 20. Round 5: slow 60, fast 40. Round 6: slow 70, fast 60. Round 7: both land on 10 and the cycle is reported. They meet back at the head because the whole list is the loop: after 7 rounds slow has gone round once and fast twice. Break the cycle and run again: fast reaches 70 after 3 rounds, finds nothing after it, and no cycle is reported.
Once slow and fast meet, put one pointer back at the head and move both one step at a time. They meet again exactly at the node where the loop begins. The Linked List Cycle page walks through this second phase.
Time: slow enters the loop within N steps, and once both are inside, fast closes the gap by one node per round, so they meet within one more lap: O(N) in total. Space: two pointers whatever the length, so O(1); a set of visited nodes would also work but costs O(N).