141 Linked List Cycle (to determine if a linked list has a ring medium)

Source: Internet
Author: User

The link list has loops, returns True, otherwise returns false

Ideas: Two pointers, a fast and slow, can meet the ring, for the empty ring

PS: Many lists of topics: You can use this idea

1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7  * };8  */9 classSolution {Ten  Public: One     BOOLHascycle (ListNode *head) { A         if(Head==null)return false; -ListNode *p1,*P2; -P1=p2=head; the          while(p2->next&&p2->next->next) {//To determine if the P->next->next is empty first to determine whether the p->next is empty, so as not to produce p->next->next not exist in the egg pain problem -P1=p1->Next; -P2=p2->next->Next; -             if(p1==p2) +                 return true; -         } +         return false; A     } at};

141 Linked List Cycle (to determine if a linked list has a ring medium)

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.