/**
* if has loop return 1 else return 0
*/
static int has_loop(List *list)
{
List *pFast;
List *pSlow;
pFast = pSlow = list;
if (pFast != NULL && pFast->next != NULL) {
pFast = pFast->next->next;
} else {
return 0;
}
while (pFast != pSlow) {
if (pFast != NULL && pFast->next != NULL)
pFast = pFast->next->next;
else
break;
pSlow = pSlow->next;
}
if (pFast == pSlow)
return 1;
else
return 0;
}
判断链表是否有环
最新推荐文章于 2025-03-12 13:16:15 发布
本文介绍了一种用于检测链表中是否存在循环的有效算法。通过使用快慢指针的方法,可以在O(n)的时间复杂度内完成检测,而空间复杂度仅为O(1)。此算法首先初始化两个指针位于链表头部,快指针每次移动两步,慢指针每次移动一步。如果链表存在循环,则快慢指针最终会相遇;若不存在循环,快指针将到达链表尾部。
475

被折叠的 条评论
为什么被折叠?



