java-linked list cycle i&&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 .

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

The first question asked whether there is a ring can be seen using a fast pointer as long as there is a ring will meet the other from the meeting point can be seen from the point of the distance between the distance ring and head to the starting point of the distance is the same as long as a pointer to the slow together with the point of the beginning of the ring if the ring size is a X and Y, respectively, x+a=y, y=2x ==>x=a; that is, the slow pointer through the distance is just the size of the ring from the point of encounter to the beginning of the ring just for the length of the whole list from head to the distance of a ring, so meet the point must be the starting code of the ring is as follows:
public class Solution {public    ListNode detectcycle (ListNode head) {        if (head==null| | Head.next==null) return null;        ListNode Slow=head;        ListNode Fast=head;        int count=0;        while (fast.next!=null&&fast.next.next!=null) {            slow=slow.next;            Fast=fast.next.next;            count++;            if (slow==fast) break  ;        }        if (slow==fast&&count!=0) {            ListNode res=head;            while (Res!=slow) {                res=res.next;                Slow=slow.next;            }            return res;        } else{            return null;}}    }

java-linked list cycle i&&linked list cycle II

Related Article

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.