Floyd's cycle-finding algorithm

本文深入探讨了弗洛伊德(Floyd)寻环算法的工作原理,特别是通过两个指针(乌龟和兔子)如何检测链表中的循环,并进一步定位循环起点的位置。文章解释了当两者首次相遇后,如何通过特定的移动策略使它们最终在循环的起始点再次相遇。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

From Quora

How does Floyd's cycle-finding algorithm work?

I understand that tortoise and hare's meeting concludes the existence of loop, but how does moving tortoise to beginning of linked list while keeping the hare at meeting place, followed by moving both one step at a time make them meet at starting point of cycle?

A lot of good perspectives.  The way I remember it is like Namrata's answer but, I think, a bit simpler without needing to explicitly manipulate any equations or worry about how many times the cycle is traversed.


We only need to consider two positions, s - the start of the cycle, and s+ x, where x is the offset from the cycle start where the two pointers meet.

When the slow pointer traveled s+ x, the fast one will have traveled an additional distance s+ x from the offset position x along the cycle.  This extra s+ x distance brought it back to the same position along the cycle (offset x). 

That means if moving a distance s+ x from that offset brings the pointer back to the offset x, then moving x less from that position, or s, will result in the pointer being at the start of the cycle - position s = offset 0. 

Therefore, starting the formerly-fast pointer from where they met (offset x along the cycle), and the formerly-slow pointer at the beginning, and moving both pointers at equal pace, after s iterations, the formerly-fast one will be at the cycle start s and, the formerly-slow one will also be at the cycle start s.




Fast pointer have to meet the slow one because their distance is s and the different of velocity is 1.
And when they meet, the slow pointer won't go further then (s+x) because s/1<(s+x)/1.(this circumstance will happen when the slow one get into the circle and the fast one is in the x)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值