Linked lists · Exercise 17 of 100
Detect a loop
Start two pointers at the head and move one by one link and the other by two links per round. If the faster pointer runs out of links, the list has an end. If there is a loop, the faster pointer gains one position per round inside it until the pointers meet.
Try it yourself
The links run from 2 to 5 to 8 to 11 to 14, then from 14 back to 8. Both pointers start at 2. At which value do they first meet after a complete round of moves?
One-step hint
Make one row per round with a slow and a fast column. Follow one arrow and two arrows respectively before comparing their positions.
Worked solution
- After one round the slow pointer is at 5 and the fast one is at 8. After two rounds they are at 8 and 14.
- In the third round the slow pointer moves to 11. The fast pointer goes from 14 through 8 to 11, so they meet at 11.