设置两个指针,一个fast一个slow
slow赋值head,fast赋值head->next
之后一直以slow指向next,fast指向next->next进行运算
如果再fast跑完前,fast和slow相遇了,则说明存在环
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
if(head==NULL||head->next==NULL)
return false;
struct ListNode *slow=head;
struct ListNode *fast=head->next;
while(slow!=fast){
if(fast==NULL||fast->next==NULL)
return false;
slow=slow->next;
fast=fast->next->next;
}
return true;
}