在《剑指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);
}
}
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
,那么如果第一个if
为while
,那么就会无限循环;如果链表长度大于 1 的话,则肯定存在 headNode.next 不为null
,那么如果第二个if
为while
, it will lead to an infinite loop.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.
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!