#include <stdbool.h>
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
*
* @param head ListNode类
* @return bool布尔型
*/
bool hasCycle(struct ListNode* head ) {
// write code here
struct ListNode* p=head;
struct ListNode* q=head;
while(p)
{
p=p->next;
if(p==NULL)
break;
if(p==q)
return true;
p=p->next; //p一次移动两个单位
q=q->next; //q一次移动一个单位
if(p==q)
return true;
}
return false;
}

京公网安备 11010502036488号