The first thing I thought after seeing the problem was:
1, how to determine whether the chain list has a ring: there is a loop is a duplicate node, then I can have traversed the node location to be stored, and then each traversal to a new node to find out just the node location of the storage and the current node is coincident, if coincident is a ring
2, the entrance of the ring: Coincident node is the entrance of the ring
3, the length of the change: Know the entrance, the node to do the next mark, and then continue to traverse, the simultaneous count of the traversal, and then traverse to this node when the count value is the length of the ring.
This method is easy to think of, but requires additional storage space, so the Internet search optimization.
1, how to determine whether the linked list has a ring
Analogy playground running, two people speed is different, then certainly will meet. Used on a linked list,
Set two pointers fast and slow, and then start the traversal. Initially all point to the Chain header node, the fast pointer moves down two nodes at a time, and the slow pointer moves down one node at a time to determine whether two pointers are the same.
If the chain list is not linked, when fast traverses to null, stops the traversal and determines that the list is not looped.
If there is a linked list, the fast pointer is bound to meet with the slow pointer on the ring, so if fast==slow, then the list has a ring.
2. Chain list length
Method One: (This is the way to see someone else's blog)
When fast and slow meet, two pointers continue to traverse at just the same speed, counting the number of steps that the next encounter will take slow the length of the ring.
Because: The second encounter, is fast put slow fell a circle, so only need to record the process of each step of the slow pointer walk How many steps is the length of the ring.
method Two: I think it's too easy. If there is an error, please remind
Fast and slow meet, fast does not move, and then slow the pointer continue to traverse (just need to slow themselves traverse, it is not more convenient, why should move together.) ), at the same time count, the next time you meet the Count value is the ring length.
3, the entrance of the ring
The length of the ring is already known in 2, when the ring entry is still two pointers to the last and next, the distance between the two pointers is length, and the pointer moves forward in one step at a time. When two pointers meet, it's the ring's entrance.
Because: Last is faster than next, and when next arrives at the ring entrance, it just goes around the ring.