[Leetcode]: 141:linked List Cycle

Source: Internet
Author: User

Topic:

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

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

Ideas:

Normal traversal, using hashset to determine whether to repeat

Code:

     Public Boolean hascycle (ListNode head) {        new  HashSet ();          while NULL ) {            if(!  Hashflag.add (head                ) {returntrue;            }             = head.next;        }         return false ;    }

Idea two: Using fast pointers and slow pointers

Two pointers, moving the speed difference one, so the fast pointer must be "catch up" slow pointer. It's sort of like a primary school chase.

Code:

     Public Booleanhascycle (ListNode head) {ListNode Fast=Head; ListNode Slow=Head;  while(slow!=NULL){            if(slow.next!=NULL&& fast.next!=NULL&& fast.next.next!=NULL) {Slow=Slow.next; Fast=Fast.next.next; if(Slow = =Fast) {                    return true; }            }            Else{                return false; }        }        return false; }

222

[Leetcode]: 141: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.