struct node 
...{
char val;
node* next;
}

bool check(const node* head) ...{} //return false : 无环;true: 有环
一种O(n)的办法就是:
设两个指针,一个每次递增一步,一个每次递增两步,如果有环的话两者必然重合,反之亦然
bool check(const node* head)
...{
if(head==NULL) return false;
node *low=head, *fast=head->next;
while(fast!=NULL && fast->next!=NULL)
...{
low=low->next;
fast=fast->next->next;
if(low==fast) return true;
}
return false;
}
本文介绍了一种高效的链表环检测方法,通过快慢指针技术实现O(n)时间复杂度内的环路判断。该算法利用两个速度不同的指针遍历链表节点,当存在环路时两者最终会相遇。
824

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



