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

后端 未结 8 499
眼角桃花
眼角桃花 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:14

    If the fast pointer moves 3 steps and slow pointer at 1 step, it is not guaranteed for both pointers to meet in cycles containing even number of nodes. If the slow pointer moved at 2 steps, however, the meeting would be guaranteed.

    In general, if the hare moves at H steps, and tortoise moves at T steps, you are guaranteed to meet in a cycle iff H = T + 1.

    Consider the hare moving relative to the tortoise.

    • Hare's speed relative to the tortoise is H - T nodes per iteration.
    • Given a cycle of length N =(H - T) * k, where k is any positive integer, the hare would skip every H - T - 1 nodes (again, relative to the tortoise), and it would be impossible to for them to meet if the tortoise was in any of those nodes.

    • The only possibility where a meeting is guaranteed is when H - T - 1 = 0.

    Hence, increasing the fast pointer by x is allowed, as long as the slow pointer is increased by x - 1.

提交回复
热议问题