Leetcode: linked list cycle [1, 141]

Source: Internet
Author: User

Tag: style blog color Io AR for SP Div 2014

[Question]

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

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


Question]

Determines whether a one-way linked list has loops.


[Idea]

Maintain the two pointers P1 and P2. Each time P1 moves one step forward, P2 moves two steps forward.
If P2 can catch up with P1, it indicates that the linked list has a ring.


[Code]
/*** Definition for singly-linked list. * struct listnode {* int val; * listnode * Next; * listnode (int x): Val (x), next (null ){}*}; */class solution {public: bool hascycle (listnode * head) {listnode * P1 = head; listnode * P2 = head; while (P2) {// P1 move forward step p1 = p1-> next; // P2 move forward two P2 = P2-> next; If (P2) P2 = P2-> next; // infer whether P2 has caught up with P1 if (P2 & p2 = p1) return true;} return false ;}};


Leetcode: linked list cycle [1, 141]

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.