测试链表是否有环的最佳算法 [英] Best algorithm to test if a linked list has a cycle
问题描述
确定链表中是否有环的最佳(停止)算法是什么?
What's the best (halting) algorithm for determining if a linked list has a cycle in it?
对时间和空间的渐近复杂性进行分析会很好,因此可以更好地比较答案.
Analysis of asymptotic complexity for both time and space would be sweet so answers can be compared better.
最初的问题不是解决出度 > 1 的节点,但有一些讨论.这个问题更像是检测有向图中循环的最佳算法".
Original question was not addressing nodes with outdegree > 1, but there's some talk about it. That question is more along the lines of "Best algorithm to detect cycles in a directed graph".
推荐答案
有两个指针遍历列表;让一个以两倍于另一个的速度迭代,并在每一步比较它们的位置.在我的头顶上,类似:
Have two pointers iterating through the list; make one iterate through at twice the speed of the other, and compare their positions at each step. Off the top of my head, something like:
node* tortoise(begin), * hare(begin);
while(hare = hare->next)
{
if(hare == tortoise) { throw std::logic_error("There's a cycle"); }
hare = hare->next;
if(hare == tortoise) { throw std::logic_error("There's a cycle"); }
tortoise = tortoise->next;
}
O(n),这是你能得到的最好的.
O(n), which is as good as you can get.
这篇关于测试链表是否有环的最佳算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!