public class Hanota { private void method(int n){
if(n>0){
method(n-1);
System.out.println("n的值:"+n);
}
}
public static void main(String[] args) {
Hanota hh=new Hanota();
hh.method(10);
}
}
大家能帮我解决下为啥结果是下面这样的啊:
n的值:1
n的值:2
n的值:3
n的值:4
n的值:5
n的值:6
n的值:7
n的值:8
n的值:9
n的值:10
if(n>0){
method(n-1);
System.out.println("n的值:"+n);
}
}
public static void main(String[] args) {
Hanota hh=new Hanota();
hh.method(10);
}
}
大家能帮我解决下为啥结果是下面这样的啊:
n的值:1
n的值:2
n的值:3
n的值:4
n的值:5
n的值:6
n的值:7
n的值:8
n的值:9
n的值:10
hh.method(10)-〉hh.method(9)...-〉hh.method(1);
到hh.method(1)时候打印出值 :1,然后跳出方法一层层网上调用,于是打出2,3...10
如果是下面这样,就会反过来。System.out.println("n的值:"+n);
method(n-1);
直到n=0时,停止递归调用,然后执行最里面那个method()的打印语句,输出 n=1....,依次类推,其实就是这样的:
n = 10;
if(10 >0 ){
n = 10 - 1;
if(9 > 0){
n = 9 - 1;
if(9 > 0){
...
{
n = 1 - 1;
if(0 > 0)
} ...
System.out.println(8);
}
System.out.println(9);
}
System.out.println(10);
}
栈后进先出
System.out.println()。就产生了这样一个效果,和java堆栈没有关系了.
如果换成下边这样:
System.out.println("n的值:"+n);
method(n-1);
那就是从10到1了
System.out.println打印
再出栈1 2 3 4 5 6 7 8 9 10
前面是递归调用