题解 | #判断链表中是否有环#
判断链表中是否有环
https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
依次访问链表节点,若链表有环,则陷入无限访问循环,而链表长度最大10000,因此当访问超过10000次,则说明有环。
#include <stdbool.h>
#include <string.h>
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
*
* @param head ListNode类
* @return bool布尔型
*/
bool hasCycle(struct ListNode* head ) {
// write code here
int flag[10005];
memset(flag, 0, sizeof(flag));
int i = 0;
flag[i] = 1;
while (head) {
if(i > 10000) return true;
i++;
head = head->next;
}
return false;
}
查看5道真题和解析