Floyd's cycle-finding algorithm

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

    The idea in the code you've found seems fine. Two fast iterators are used for convenience (although I'm positive such kind of 'convenience', like putting a lot of 'action' in the condition of while loop, should be avoided). You can rewrite it in more readable way with one variable:

    while (fastNode && fastNode.next()) {
        if (fastNode.next() == slowNode || fastNode.next().next() == slowNode) {
            return true;
        }
        fastNode = fastNode.next().next();
        slowNode = slowNode.next();
    }
    

提交回复
热议问题