How to determine whether there are circles in a singly linked list?
Answer:let to point p1 ,and p1 , p1 travels the list with one step length ,and p2 with two step length ,
After t step , if p2 come to same pos with p1 , we get there is an circle , otherwise no circle exist in list.
Now let’s prove it .
Both p1 and p2 travel the list ,but with diff step length, where p1 is a one step traveler and P2 is a two step traveler.
Exist and only exist two conditions:
1. Condition one: P2 come to the end. we get there is on circle , it’s trival.
2. Condition two:P2 come to same pos with p1, we got more than one circle exist.
Let there is a circle as the picture below:
Suppose: When p1 come to the first pos (N1) of the circle, P2 is at pos Nk(where K should be one of 1…N).
After t step :
P1 come to N(t1) where t1=t%N
P2 come to N(t2) whereK2=(k+2t)%N
Principal :
t , t is a natural number , let t+n*m=k+2t , so t1=t2 and P1 come to same pos with P2. where m is natural number
Proof:
Let t=m*n-k we get it, m is a positive natural number.
口.
本文介绍了一种检测单链表中是否存在环的有效方法。通过设置两个指针,一个每次移动一步,另一个每次移动两步,如果存在环,两个指针最终会在环内相遇。该方法简单且有效,避免了额外的空间开销。


被折叠的 条评论
为什么被折叠?



