#include <stdbool.h>
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
*
* @param head ListNode类
* @return bool布尔型
*/
bool hasCycle(struct ListNode* head ) {
//思路
//使用快慢指针,若二者相遇,则表示有环
struct ListNode* fast = head;
struct ListNode* slow = head;
if (head == NULL) {
return false;
}
while ((slow != NULL) && (fast != NULL) && (fast->next != NULL)) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
return true;
}
}
return false;
}



京公网安备 11010502036488号