"Linked list" Linked list Cycle

Source: Internet
Author: User

Topic:

Given A linked list, determine if it has a cycle in it.

Ideas:

For judging whether the chain list has a ring, the method is very simple, with two pointers, beginning to point to the head node, one is a fast pointer, two steps at a time, a slow pointer, one step at a time, when two pointers coincide with the existence of the ring.

Fast first into the ring, after the slow entered, if the slow as in front, fast in the back of each loop to slow near 1, so will meet, and will not appear fast directly skip slow situation.

/** Definition for singly-linked list. * Function ListNode (val) {* This.val = val; * This.next = null; *} 
    *//** * @param {listnode} head * @return {Boolean}*/varHascycle =function(head) {if(head==NULL|| head.next==NULL){        return false; }        vars=head,f=Head.next.next;  while(s!=f) {        if(f==NULL|| f.next==NULL){            return false; }Else{s=S.next; F=F.next.next; }    }        return true;};

"Linked list" Linked list Cycle

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.