思路:可以定义两个快慢指针一个快于一个,只要两个指针相遇则证明有环,否则返回false。
代码:
bool hasCycle(struct ListNode *head)
{
struct ListNode* fast = head;
struct ListNode* slow = head;
if(fast == NULL && slow == NULL )
{
return false;
}
while(fast != NULL && fast->next != NULL)
{
fast = fast->next->next;
slow = slow->next;
if(fast == slow)
{
return true;
}
}
return false;
}