Using the tortoise-hare algorithm (detecting the cycle of floyds), ​​we can find the cycle in this list.
ie If we move two pointers, one at speed 1 and the other at speed 2, they will occur if the linked list has a loop. What for? Think of two cars moving along a track - the faster the car will always go slower!
The hard part here is finding the beginning of the cycle. Imagine how an analogue, two people rush along a track, one running twice as fast as the other. If they start in the same place, when will they follow next time? They will follow at the beginning of the next lap.
Thus, after defining the loop, if we move n1 back to Head and save n2 to MeetingPoint and move them both at the same pace, they will meet in LoopStart (Meeting Item).
Then, to find the length, move n1 back to the head and set the length variable. Now change the length of the variable at each step. After idetifying LoopStart, save n1 ptr as such and move n2 ptr and inc length for each move. When n2-> next == n1, return the length .
This will be O (N) runtime, O (1) space complexity
source share