判断给定的链表中是否有环
扩展:
你能给出O(1)空间复杂度的解法么?
//快慢指针能够相遇则说明有环
#include <stdbool.h>
bool hasCycle(struct ListNode* head ) {
if(head==NULL)return false;
// write code here
struct ListNode *p=head;
while(p!=NULL&&p->next!=NULL)
{
p=p->next->next;
head=head->next;
if(p==head)return true;
}
return false;
}