题解 | #判断链表中是否有环#
判断链表中是否有环
https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
#include <stdbool.h>
#include <stdio.h>
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
*
* @param head ListNode类
* @return bool布尔型
*/
bool hasCycle(struct ListNode* head ) {
// write code here
struct ListNode* low = head;
struct ListNode* fast = head;
int q=0;
while(fast != NULL && fast->next != NULL){
if(low->next == fast->next->next){
struct ListNode* head1 = head;
struct ListNode* head2 =low->next;
while(head1 != head2){
head1 = head1->next;
head2 = head2->next;
q++;//计算环的入口
}
return true;
}
low = low->next;
fast = fast->next->next;
}
return false;
}
查看6道真题和解析