Given a linked list, return the node where the cycle begins. If There is no cycle, return null .
Note:do not modify the linked list.
Using the fast and slow pointer,
Fast advances two steps at a time (null is returned if NULL is present in two steps).
Slow is further (returns NULL if NULL is present) each time before.
When there is a loop, there is always a time when fast will catch up with slow (meet) and prove the following:
1, if fast sets slow ring before slow two steps behind, then Fast2slow1 after, fast in the slow rear step, enter (2)
2, if fast sets slow ring before slow one step behind, then Fast2slow1 after, fast catch up with slow (meet)
All other conditions can be attributed to the above two steps.
Assuming that the entry steps are X from head to ring entry, the loop length is Y, and the distance from entry is m when met
Then Fast:x+ay+m,slow:x+by+m (A > B)
X+ay+m = 2 (x+by+m)
Finishing x+m = (a-2b) y
The meaning of the above formula is that the position of the encounter (m) and then the X-step forward, exactly the full multiple of Y is the whole circle.
The question now is how to count X.
The length of the head to entry is X, as long as fast is further from the head each time before, slow from the encounter position each time before further,
The entrance to the ring when we meet again.
/*** Definition for singly-linked list. * Class ListNode {* int val; * ListNode Next; * ListNode (int x) {* val = x; * next = NULL; * } * } */ Public classSolution { PublicListNode detectcycle (ListNode head) {if(Head = =NULL|| Head.next = =NULL)return NULL; ListNode Slow=Head; ListNode Fast=Head; while(Fast! =NULL&& Fast.next! =NULL) {Slow=Slow.next; Fast=Fast.next.next; if(Slow = =fast) Break; } if(Fast = =NULL|| Fast.next = =NULL)return NULL; Slow=Head; while(Slow! =fast) {Slow=Slow.next; Fast=Fast.next; } returnslow; }}
142. Linked List Cycle II