LeetCode | Linked List Cycle

题目:

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

Follow up:

Can you solve it without using extra space?

思路:

利用快慢指针来判断是否有环。为了防止时间太长,我设置了计时器。

代码:

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

    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/17309079
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞