#include <stdbool.h>
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
*
* @param head ListNode类
* @return bool布尔型
*/
typedef struct ListNode ListNode;
bool hasCycle(struct ListNode* head ) {
if(head==NULL||head->next==NULL){
return false;
}
// write code here
//快慢指针
//快指针走两步,慢指针走1步,如果快指针等于慢指针则就是为环
ListNode* slow=head;
ListNode* fast=head->next;
while(slow!=fast){
if(fast==NULL||fast->next==NULL){
return false;
}
slow=slow->next;
fast=fast->next->next;
}
return true;
}

京公网安备 11010502036488号