使用 C# 在 LinkedList 中进行循环检测
在面试问题中,“实现一种检测循环存在的算法。”。例如链表有环,如:
0--->1---->2---->3---->4---->5---->6
▲ |
| ▼
11<—-22<—-12<—-9<—-8
利用Floyd的环检测,可以通过使用fast & 来解决这个问题。慢指针。那么我应该尝试比较
a. 链接的节点值,即
if (fast.data == slow.data)
break;
快和慢的类型为Link
class Link
{
int IData {get; set;}
Link Next {get; set;}
}
OR
b。 它们是否指向相同的引用,即if(快==慢)
谢谢。
In the interview question, "Implement an algorithm which detects for presence of the loop.". For example, the linked list has a loop, like:
0--->1---->2---->3---->4---->5---->6
▲ |
| ▼
11<—-22<—-12<—-9<—-8
Using Floyd's cycle detection, this problem can be solved by using a fast & slow pointer. So should I try comparing
a. Link's node values, i.e.
if (fast.data == slow.data)
break;
where fast and slow are of type Link
class Link
{
int IData {get; set;}
Link Next {get; set;}
}
OR
b. Are they pointing to same reference, i.e. if (fast == slow)
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
希望这会有所帮助......这可能很天真,但它有效......
Hope this helps... It might be naive but it works...
您应该只比较节点本身。毕竟,有一个包含重复数据的链表是合理的,但实际上没有循环。
我也将它们称为节点而不是链接。链接只是从一个节点到下一个或上一个节点的引用 - 特别是,没有与链接关联的数据,仅与节点关联。
You should only be comparing the nodes themselves. After all, it's reasonable to have a linked list with repeated data in, without it actually having a cycle.
I would call them nodes rather than links too. A link is simply the reference from one node to the next or previous one - in particular, there's no data associated with a link, only with a node.