最好的算法,以测试是否链表具有周期 [英] Best algorithm to test if a linked list has a cycle

查看:96
本文介绍了最好的算法,以测试是否链表具有周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是最好的(停止)的算法来确定,如果一个链表有一个周期呢?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆