Floyd's cycle-finding algorithm

前端 未结 3 1889
心在旅途
心在旅途 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:35

    This algorithm will find a cycle in a linked list.
    one fast node can be used instead:

     function boolean hasLoop(Node startNode){
      Node slowNode = Node fastNode = startNode;
      while (slowNode && fastNode = fastNode.next() && fastNode = fastNode.next()){
        if (slowNode == fastNode) return true;
        slowNode = slowNode.next();
      }
      return false;
    }
    

提交回复
热议问题