Floyd's cycle-finding algorithm

前端 未结 3 1874
心在旅途
心在旅途 2021-02-10 07:48

I\'m trying to find this algorithm on C++ in .NET but can\'t, I found this one:

// Best solution
function boolean hasLoop(Node startNode){
  Node slowNode = Node         


        
3条回答
  •  悲哀的现实
    2021-02-10 08:39

    The algorithm is correct. Proof:

    The case of no cycle is trivial: the hare will find the end of the list.

    So, there's a cycle, and the hare enters it, running around like crazy. Eventually, the tortoise reaches the first node of the cycle. From this point on, both necessarily stay in the cycle: the only way they can go from a node is to the next node, which eventually leads back to the first node of the cycle. (Draw a picture of the list/graph to convince yourself.)

    Since the hare moves faster, it will eventually catch up with the tortoise. Depending on the length of the cycle and the number of nodes traversed before entering it (whether they are odd or even is what matters, so there are four cases), this may happen after an odd or an even number of steps. That's why the hare should check both its current node and the next node for the tortoise's presence. (The example code uses two pointers to achieve this, though that's not really necessary.)

    For a more formal proof, check out this Wikipedia page.

提交回复
热议问题