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.

Follow up:
Can you solve it without using extra space?

Assuming head to ring position distance is a, two pointer meet distance ring start position B

2 (A + b + mcycle) = a + B + ncycle;

=>a+b = (n-m) Cycle

A = (n-m) cycle-b;

So the first two pointer meet position and head down together, the position that meet again is the cycle start point.

 PublicListNode detectcycle (ListNode head) {if(Head = =NULL)return NULL; varslow =Head; varFast =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; }    

Scaling issues

Http://www.cnblogs.com/hiddenfox/p/3408931.html

In the online collection of some of the problems related to the question, the idea of a lot of open, summed up as follows:

1. What is the length of the ring?

2. How do I find the first node in the ring (that is, linked list Cycle II)?

3. How to turn a linked list into a single linked list (release ring)?

4. How can I tell if there is an intersection of two single-linked lists? How do I find the first node that intersects?

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.