思路

image-20241105102925107

这题要用到快慢指针

一个环形链表我们定义一个fast和一个slow,让他们开始向前遍历,fast走得快slow走得慢,如果是环形链表,那么他们肯定会相遇,如果不是那么fast总会走到null

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
bool hasCycle(struct ListNode *head) {
if(head==NULL){
return false;
}
struct ListNode*fast=head->next;
struct ListNode*slow=head;
while(fast!=NULL&&fast->next!=NULL){
fast=fast->next->next;
slow=slow->next;
if(fast==slow){
return true;
}
}
return false;
}