class Solution {
public:
bool hasCycle(ListNode *head) {
//链表不为空
if(head == nullptr || head->next == nullptr )
{
return false;
}
ListNode* fast = head;
ListNode* slow = head;
while(fast)
{ //快慢指针各走一步
fast = fast->next;
slow = slow->next;
//只有一个值时
if(!fast)
{
return false;
}
//快指针再走一步
fast = fast->next;
//相等即有环
if(fast == slow)
{
return true;
}
}
//循环结束没有环
return false;
}
};