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

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

    If the linked list has a loop then a fast pointer with increment of 2 will work better then say increment of 3 or 4 or more because it ensures that once we are inside the loop the pointers will surely collide and there will be no overtaking.

    For example if we take increment of 3 and inside the loop lets assume

    fast pointer --> i  
    slow         --> i+1 
    the next iteration
    fast pointer --> i+3  
    slow         --> i+2
    

    whereas such case will never happen with increment of 2.

    Also if you are really unlucky then you may end up in a situation where loop length is L and you are incrementing the fast pointer by L+1. Then you will be stuck infinitely since the difference of the movement fast and slow pointer will always be L.

    I hope I made myself clear.

提交回复
热议问题