Leetcode------Linked List Cycle II

Source: Internet
Author: User

Title: Linked List Cycle II
Pass Rate 30%
Difficulty Medium

See the Linked List Cycle I before looking at the upgrade version

Reading the first version will help with the second version, first understand the structure of the ring. Then look at the following picture:

Assuming that the fast and slow pointer is at the intersection of the dividend ring, the starting point of the ring is K, then:

1, the fast hand walk is twice times the slow pointer walk.

2, the slow pointer to meet point when walking path is: x+y

3, the fast pointer to meet the point of walking path is: x+y+z+y=x+2y+z

4, and because 1, all have x+y=x+2y+z

5, Draw: X=z

So we found that the starting point and the coincident point to the beginning of the loop is the same amount of distance. Then we put two pointers from these two places to start the traversal, when again coincident is the loop start point, the specific code is as follows:

1  Public classSolution {2      PublicListNode detectcycle (ListNode head) {3         if(head==NULL)return NULL;4         if(head.next==NULL)return NULL;5         if(head.next.next==NULL)return NULL;6         7ListNode slow=head;8ListNode fast=head;9         Ten          while(fast!=NULL&& fast.next!=NULL){ Oneslow=Slow.next; Afast=Fast.next.next; -             if(fast==slow) { -slow=head; the                  while(slow!=fast) { -slow=Slow.next; -fast=Fast.next; -                     } +                 returnfast; -             } +         } A  at         return NULL; -          -     } -}

Leetcode------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.