【问题标题】:Resolving Stacks with Return Statements使用返回语句解析堆栈
【发布时间】:2023-03-16 15:15:01
【问题描述】:

虽然我认为我对在 void 方法中解析堆栈有深入的了解,但 return 方法确实混淆了我对堆栈的理解。以下方法特别让我感到困惑,因为我原以为它会返回 0,但会返回 12。

public static int mystery(int n) { // where the method call is mystery(7)
    n--; // since n is decremented before the first 
         // recursive method, the first stack is method(6)

    if(n > 0)  // base case
       mystery(n);

    return n * 2; // 0 * 2 = 0?
}

我的问题是为什么方法在神秘(7)时输出 12,如果 0 是进入堆栈的最后一个值。这种方法不还是遵循LIFO吗?

【问题讨论】:

  • 仔细看。递归调用不影响结果! (7 - 1) * 212
  • 由于你的方法从来没有returns 是递归调用的结果,实际上返回给main的是第一个调用n==2
  • @GBlodgett 更准确地说,该方法确实在递归调用中返回值,但该值从未使用过。第一个电话也是7
  • @Jai 但是递归调用从来没有返回语句,那么它如何返回值?
  • @Letta 你在递归调用mystery(),这个方法返回一个int,所以它肯定会在那里返回一个int。并且每个栈中n的值属于特定栈,没有“通用”n被所有栈共享。

标签: java recursion return


【解决方案1】:

我们不考虑 7。假设您的值为 3。mystery(3)。在这种情况下,该函数将运行 3 次。

第一次运行:

n = 3;
n--; // n = 2
(n > 0) so mystery(2)

第二次运行:

n = 2;
n--; // n = 1
(n > 0) so mystery(1)

第三轮:

n = 1;
n--; // n = 0
(n = 0) so return the n*2 . And the return will be 4

为什么?导致递归函数不会改变n的值

【讨论】:

    【解决方案2】:

    必须是这样的:

    public static int mystery(int n) { // where the method call is mystery(7)
    
    n--; // since n is decremented before the first 
         // recursive method, the first stack is method(6)
    
    if(n > 0)  // base case
       n = mystery(n);
    
    return n * 2; // 0 * 2 = 0?
    }
    

    现在它将始终返回 0。

    【讨论】:

      【解决方案3】:

      由内而外:

      mystery 的最内层调用(n 为 1 进入)返回 0 给它的调用者。不使用返回值。

      mystery 的下一级(n 为 2 进入)返回 2 给它的调用者。不使用返回值。

      ...等等...

      mystery 的下一个最外层(输入时 n 为 6)向其调用者返回 10。不使用返回值。

      mystery 的最外层(入口时 n 为 7)返回 12 给它的调用者,这是最终的返回值。

      【讨论】:

        猜你喜欢
        • 2015-03-10
        • 2020-08-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-05
        • 1970-01-01
        • 2020-12-10
        • 2021-01-27
        相关资源
        最近更新 更多