我在网上看了一些面试问题,关于你将如何找到,如果有一个链表循环和解决方案(Floyd的循环查找算法)是有两个指针,一个是比其他快两倍,并检查他们再见面的。
I read some interview question online about how would you find if there's a loop in a linked list, and solution (Floyd's cycle-finding algorithm) is to have two pointers, one is 2x faster than the other, and check if they meet again.
我的问题是:为什么我不能只保留一个指针不动,只需将其他指针向前每次1步
My question is: Why can't I just keep one pointer fixed, just move the other pointer forward by 1 step each time?
由于第一(非移动)指针可能不会说谎的内环路,所以指针永远不会满足。 (请记住,一个循环可以由该列表的一部分的。)
Because the first (non-moving) pointer might not lie within the loop, so the pointers would never meet. (Remember that a loop may consist of only part of the list.)