142. Linked List Cycle II

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.