Redian新闻
>
How can one determine whether a singly linked list has a cycle?
avatar
How can one determine whether a singly linked list has a cycle?# JobHunting - 待字闺中
b*n
1
Keep 
track 
of
 two 
pointers 
in the linked&
#8233; list,
 and 
start 
them
 at 
the

beginning 
of 
the 
linked 
list.


At 
each 
iteration 
of 
the 

algorithm,
advance 
the 
first
 pointer 
by
one 
node 
and 
the
 second
 pointer by

two 
nodes.


If 
the 
two 
pointers 
are

ever 
the 
same 
(other 
than 
at
 the
beginning 
of
 the
 algorithm), 
then 
there &
#8233;is
 a 
cycle.


If
 a
 pointer
 ever 
reaches

the 
end
 of
 the
 inked
 list
 before
the
 pointers 
are 
the 
same,
 then there
8233;is 
no 
cycle.

我看到的答案是这样的。但是我觉得不太对啊,比如 node1 指向 node2 指向 node3
指向 node4 指向 node5 指向 node6 指向 node2
avatar
g*u
2
they will meet at node 6.

linked&
8233;
8233;
&

【在 b****n 的大作中提到】
: Keep 
track 
of
 two 
pointers 
in the linked&
: #8233; list,
 and 
start 
them
 at 
the

: beginning 
of 
the 
linked 
list.
: 

At 
each 
iteration 
of 
the 

: algorithm,
advance 
the 
first
 pointer 
by
: one 
node 
and 
the
 second
 pointer by

: two 
nodes.
: 

If 
the 
two 
pointers 
are

: ever 
the 
same 
(other 
than 
at
 the
: beginning 
of
 the
 algorithm), 
then 
there &

avatar
b*n
3
为什么呢?
第1步: pointer 1 at node 1; pointer 2 at node 1;
第2步: pointer 1 at node 2; pointer 2 at node 3;
第3步: pointer 1 at node 3; pointer 2 at node 5;
第4步: pointer 1 at node 4; pointer 2 at node 2; (结束)
还是说,至此不算结束,还继续?
第5步: pointer 1 at node 5; pointer 2 at node 4;
第6步: pointer 1 at node 6; pointer 2 at node 6;
答案其实还有一句,就是说pointer 2不一定要只跳一格,可以每次跳n (n>1)格,
那么,是不是说,根据圈的大小,有时候要绕比较多圈,两个pointer才刚好遇得上?
而且,反正有圈,两个pointer如果遇不上,就会一直转下去?
avatar
z*8
4
这当然不算结束
n->next == NULL 才算结束, 有环的情况永远不会结束,直到相遇

【在 b****n 的大作中提到】
: 为什么呢?
: 第1步: pointer 1 at node 1; pointer 2 at node 1;
: 第2步: pointer 1 at node 2; pointer 2 at node 3;
: 第3步: pointer 1 at node 3; pointer 2 at node 5;
: 第4步: pointer 1 at node 4; pointer 2 at node 2; (结束)
: 还是说,至此不算结束,还继续?
: 第5步: pointer 1 at node 5; pointer 2 at node 4;
: 第6步: pointer 1 at node 6; pointer 2 at node 6;
: 答案其实还有一句,就是说pointer 2不一定要只跳一格,可以每次跳n (n>1)格,
: 那么,是不是说,根据圈的大小,有时候要绕比较多圈,两个pointer才刚好遇得上?

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。