【问题标题】:Can some one explain me the following Java snippet for recursion?有人可以向我解释以下用于递归的 Java 片段吗?
【发布时间】:2020-08-17 06:19:44
【问题描述】:
public class GetElementWithoutPop {

    public static void main(String args[]) {
        Stack<Integer> stack = new Stack<Integer>();
        stack.push(10);
        stack.push(20);
        stack.push(30);
        stack.push(40);
        stack.push(50);
        stack.push(60);
        System.out.println("value is: " + GetElementWithoutPop.getStackElement(stack, 3));
        System.out.println("stack is " + stack);

        // Using Java
        int position = 3;
        Integer result = stack.get(position);
        System.out.println(result);
    }

    public static <T> T getStackElement(Stack<T> stack, int index) {
        if (index == 0) {
            return stack.peek();
        }

        T x = stack.pop();
        try {

            return getStackElement(stack, index - 1);
        } finally {
            stack.push(x);
        }
    }

}

直到索引从 3 变为 0 这一切都很好而且很简单,但之后代码返回到 try 块,然后再次返回到 finally 块并且索引开始自行增加,一直返回到3 和stack.push(x) 将堆栈恢复到其原始状态。

这是怎么回事?
对递归相当陌生,我需要了解这一点!

【问题讨论】:

    标签: java recursion stack


    【解决方案1】:

    发生这种情况是因为每个函数调用对于同一个函数都有自己独特的上下文,因此变量 x 存储弹出的变量并递归调用以弹出更多值,但该值存储在下一个函数调用的 x 中,同时返回 finally块运行并再次推送每个函数调用中 x 的每个唯一值

    T x = stack.pop();           // this value remains stored in the function call stack
        try {
    
            return getStackElement(stack, index - 1);  // same function runs for further case (n-1) th and stores the value in its own x variable in its context
        } finally {
            stack.push(x);      // after the control returns, this copy of function has its  unique x variable and that is pushed again
        }
    

    您提到“索引开始自行增加到 3 ..”,这是因为每个函数调用都有自己的一组变量,包括索引

    一些步骤

    1) 索引为 3 的函数调用实例调用索引为 2 的函数

    2) 索引为 2 的函数调用实例调用索引为 1 的函数

    3) 索引为 1 的函数调用实例调用索引为 0 的函数

    4) 控制返回

    5) 现在控件返回到索引值为 1 的实例

    6) 控制甚至从那个实例返回,现在返回到索引为 2 的实例

    这就像缠绕然后展开,在解决递归问题时,我们必须经常决定是否要在调用 n 然后调用 n-1 或调用 n-1 时做一些工作,让控制返回然后做一些工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-19
      • 1970-01-01
      • 2012-04-09
      • 1970-01-01
      • 2023-02-08
      • 2012-06-13
      • 2018-05-09
      • 1970-01-01
      相关资源
      最近更新 更多