简体   繁体   English

在 java 中将 while 循环转换为递归

[英]Converting while loop to recursion in java

Hi I'm trying to convert this java while loop code into recursion.您好我正在尝试将此 java while 循环代码转换为递归。 I have tried converting it into recursion but I keep getting an error.我尝试将其转换为递归,但我不断收到错误消息。 the while loop works fine is just when I convert it into recursion is when I get an error.当我将它转换为递归时,while循环工作正常,当我遇到错误时。 Any help on how to convert it into recursion will be appreciated, Thank you.任何有关如何将其转换为递归的帮助将不胜感激,谢谢。

public static boolean hasCycle( Node head) {
    Node slow = head;
    Node fast = head; 
    boolean loop = false; 
    while (slow != null && fast != null && fast.getNext() != null) {
        slow = slow.getNext();
        fast = fast.getNext().getNext();

        if(slow == fast) {
            loop = true;
            break;
        }
    }
    return loop;

}

//recursion code //递归代码

    Node slow = head;
    Node fast = head; 
    boolean loop = false; 

    if(slow == fast) {
        return true;
    }else if(slow != fast) {
        if(slow.getNext() != null) {
            return hasCycle(slow.getNext());
        }
        return false;
    }else {
        if(fast.getNext() != null) {
            return hasCycle(fast.getNext());
        }
        return false;
    }

You seem to only be checking for immediate loops in your first iterative version.您似乎只在第一个迭代版本中检查即时循环。 (You are not checking if you have a larger loop A -> B -> C -> A. You are only checking for loops like A -> B -> A). (您没有检查是否有更大的循环 A -> B -> C -> A。您只检查像 A -> B -> A 这样的循环)。 I assume that what you presented is correct and what you want, albeit strange.我假设您提出的内容是正确的,并且是您想要的,尽管很奇怪。 (If you have a larger loop it will go on infinitely). (如果你有一个更大的循环,它将无限地打开 go)。

The proper and simpler way to do what you presented recursively is:以递归方式执行您提出的操作的正确且更简单的方法是:

public boolean hasImmediateCycle(Node node) {
   if (node == null || node.getNext() == null) {
      return false;
   } else if (node == node.getNext().getNext()) {
      return true;
   } else {
      return hasImmediateCycle(node.getNext());
   }
}

If you wanted to make it check for all possible loops you would need to do it slightly differently:如果你想让它检查所有可能的循环,你需要做的稍微不同:

private boolean hasCycle(Node node, Set<Node> seen) {
   if (node == null) {
      return false;
   } else if (seen.contains(node)) {
      return true;
   } else {
      seen.add(node);   
      return hasCycle(node.getNext(), seen);
   }
}

public boolean hasCycle(Node node) {
  return hasCycle(node, new HashSet<Node>());
}

This will check all the seen nodes in case they appear again in the next reference.这将检查所有seen的节点,以防它们再次出现next参考中。 This actually uses the .equals() and .hashCode() of your Node so it is important they are implemented consistently with each other.这实际上使用了Node.equals().hashCode() ,因此它们彼此一致地实现很重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM