【发布时间】:2020-12-14 23:41:59
【问题描述】:
所以我试图实现一个函数来检测链表中的循环,基本上,我一直在苦苦挣扎,直到我意识到我只需要切换 2 个条件。
此代码不起作用,它会产生 SIGSEV 错误:
bool has_cycle(SinglyLinkedListNode* head) {
struct SinglyLinkedListNode *slow = head;
struct SinglyLinkedListNode *fast = head;
while(slow && fast->next && fast)
{
fast = fast->next->next;
slow = slow->next;
if(fast == slow)
{
return 1;
}
}
return 0;
}
但是当我将while(slow && fast->next && fast) 切换为while(slow && fast && fast->next) 时,它可以工作。为什么?
【问题讨论】:
-
while(slow && fast && fast->next)Google 用于“短路评估”
标签: c data-structures while-loop linked-list