[LeedCode OJ] #141 Linked List Cycle,

Source: Internet
Author: User

[LeedCode OJ] #141 Linked List Cycle,

[Disclaimer: All Rights Reserved. indicate the source for reprinting. Do not use it for commercial purposes. Contact mailbox: libin493073668@sina.com]


Link: https://leetcode.com/problems/linked-list-cycle/


Question:

Give a linked list and determine whether the linked list has loops.


Ideas:

Set the speed pointer. The speed pointer takes two steps at a time, and the slow pointer takes one step at a time. If the fast pointer reaches NULL, it indicates that there is no loop. Once the fast pointer is equal to the slow pointer, it indicates that there is a loop.


/** * 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)    {        if(head==NULL)            return false;        ListNode *fast,*slow;        fast = slow = head->next;        while(fast!=NULL&&fast->next!=NULL)        {            fast = fast->next->next;            slow = slow->next;            if(fast==slow)                return true;        }        return false;    }};


Copyright Disclaimer: This article is the original article of the blogger. If it is reproduced, please indicate the source

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.