Home  >  Q&A  >  body text

java - if与while的区别?

在《剑指offer》的面试题5:“从尾到头打印链表”,在使用递归时,为什么不能用while来代替if?

    public static void printListReverse_recursively(listNode headNode){
        if(headNode!=null)
        {
            if(headNode.next!=null)
            {
                printListReverse_recursively(headNode.next);
            }
            System.out.println(headNode.data);
            
        }
    }
PHPzPHPz2676 days ago568

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-04-18 10:53:48

    Absolutely not - you can write a small demo yourself and try it, you will know. No matter which one you use if 换成 while,都会导致无限循环 —— 因为如果链表长度不为 0 的话,则肯定存在 headNode 不为 null,那么如果第一个 ifwhile,那么就会无限循环;如果链表长度大于 1 的话,则肯定存在 headNode.next 不为 null,那么如果第二个 ifwhile, it will lead to an infinite loop.

    reply
    0
  • 迷茫

    迷茫2017-04-18 10:53:48

    if is a conditional judgment, while is a loop structure. One will only be executed once, and the other will be executed several times until the condition is false.

    reply
    0
  • PHPz

    PHPz2017-04-18 10:53:48

    Recursion is that the difference between if and while is that if will only be judged once, regardless of whether the code will be executed, if will not go back to judge again (some people say "will never look back").
    If the while expression is true, it will look back and judge multiple times (go back and judge again) until the condition is not met.

    If the values ​​in the linked list are 1, 2, 3, 4; using if, 1, 2, 3, 4 will be output as normal output.
    With while, the first 1 is not empty, which causes the first while (headNode.next!=null) condition to always be true, which will create an infinite loop.
    If what I said is correct, I hope you will adopt it, thank you!

    reply
    0
  • Cancelreply