Floyd's Cycle-Finding Algorithm

s --a-- begin --x----meet point
        |                |
        |----------------|


1.fast goes two steps each time, while slow goes one step each time.

2.Supposing slow goes d, then fast goes 2*d. Considering the fast goes n loops, the distance of fast goes is d+ n*r, where r is the circle of loop. Then, 
2*d = d+ n*r
d = n*r

d = a + x = n * r = (n-1)*r + r
  = (n-1)*r + L-a               // L is the length of the list

a = (n-1)*r + L-a-x     
It means the distance from start point to the start of loop is equal to the distance from meet point moving to the start of loop. 

你可能感兴趣的:(Floyd's Cycle-Finding Algorithm)