Http://www.gocalf.com/blog/circle-of-link-list.html
Problem Description: In a one-way list, each node contains a pointer to the next node, and the pointer to the last node is set to null. But if the pointer to the last node points to a node in the list, it will form a ring, in order to traverse the list, the program will fall into a dead loop. Our problem is how to detect whether a link is in a linked list, and if a loop is detected, how to determine the entry point of the ring (that is, the length of the loop and the chain length in front of the ring).
A more space-consuming approach is to by traversing the list from scratch, depositing each access node (or its address) into a set (HashSet) or Dictionary (dictionary), if a node is found to have been accessed, it means that the linked list has a ring, and that the node is the entry point of the ring. This requires O (n) space and O (n) time, where N is the number of nodes in the list.
If the requirement is only O (1) space, O (N) time, what should be done.
Actually very simple, imagine running on the runway: two of different speed people on the playground on the track of a lap, they always meet. So we just have to prepare two pointers, starting from the head of the chain, one step at a time, the other two steps forward at a time. If the list does not have a ring, then a second (faster) pointer will reach the end point, but if there is a ring in the list, two pointers will circle in the loop and meet at some point.
You may ask how many laps the two pointers will take to meet each other in the loop. will not be able to turn thousands of tens of thousands of laps can not meet. In fact, before the first (slow) pointer turns full circle in the loop, two pointers must meet. You may set the ring length to L, the first pointer P1 the first entry into the loop, the second pointer P2 in the P1 (0< a < L), where the two pointers meet after X move, then there should be 0 + x = a + 2x (ModL), apparently x = l-a. The following diagram shows a clear picture of this relationship, after X =l-a move, the P1 moved forward l-a position (equivalent to a back up a), to the p1′, and P2 moved forward 2l-2a position (equivalent to back 2a), to p2′, obviously p1′ and p2′ are the same point.
Two_pointers_in_ring
The slow pointer (P1) is bound to meet the fast pointer (P2) within a week.
In the know linked list has a ring, ask the ring is a very simple thing, as long as from that meeting point, fixed P2, continue to move P1, until P1 and P2 meet again, the number of steps is ring long.
How do you find the length of the chain in front of the ring? Quite simply, let P1 and P2 all go back to the starting point of the list, and then let P2 go forward first (each step forward), then P1 and P2 go forward at the same time, when they meet again, the number of steps that P1 take is the length of the chain in front of the ring.