Why increase pointer by two while finding loop in linked list, why not 3,4,5?

后端 未结 8 500
眼角桃花
眼角桃花 2020-12-04 05:29

I had a look at question already which talk about algorithm to find loop in a linked list. I have read Floyd\'s cycle-finding algorithm solution, mentioned at lot of places

8条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-04 06:18

    Consider a cycle of size L, meaning at the kth element is where the loop is: xk -> xk+1 -> ... -> xk+L-1 -> xk. Suppose one pointer is run at rate r1=1 and the other at r2. When the first pointer reaches xk the second pointer will already be in the loop at some element xk+s where 0 <= s < L. After m further pointer increments the first pointer is at xk+(m mod L) and the second pointer is at xk+((m*r2+s) mod L). Therefore the condition that the two pointers collide can be phrased as the existence of an m satisfying the congruence

    m = m*r2 + s (mod L)

    This can be simplified with the following steps

    m(1-r2) = s (mod L)

    m(L+1-r2) = s (mod L)

    This is of the form of a linear congruence. It has a solution m if s is divisible by gcd(L+1-r2,L). This will certainly be the case if gcd(L+1-r2,L)=1. If r2=2 then gcd(L+1-r2,L)=gcd(L-1,L)=1 and a solution m always exists.

    Thus r2=2 has the good property that for any cycle size L, it satisfies gcd(L+1-r2,L)=1 and thus guarantees that the pointers will eventually collide even if the two pointers start at different locations. Other values of r2 do not have this property.

提交回复
热议问题