【问题标题】:How to implement recursive function only using stacks?如何仅使用堆栈实现递归函数?
【发布时间】:2020-02-09 04:58:38
【问题描述】:

我有一个分配给我递归函数,并且必须只使用堆栈重写它(无递归)。我不知道如何实现以下功能

public static void fnc1(int a, int b) {
    if (a <= b) {
        int m = (a+b)/2;
        fnc1(a, m-1);
        System.out.println(m);
        fnc1(m+1, b);
    }
}

问题是我无法弄清楚如何在存在头尾递归的情况下实现递归函数。

我尝试遍历堆栈,每次弹出一个值 (a, b) 并推送一个新值 (a, m-1) 或 (m+1, b) 而不是调用“fnc1()”,但输出总是乱码。

编辑: 这是我尝试的代码:

public static void Fnc3S(int a, int b) {
        myStack stack1_a = new myStack();
        myStack stack1_b = new myStack();

        myStack output = new myStack();

        stack1_a.push(a);
        stack1_b.push(b);

        while(!stack1_a.isEmpty()) {

            int aVal = stack1_a.pop();
            int bVal = stack1_b.pop();
            if(aVal <= bVal) {
                int m = (aVal+bVal)/2;

                stack1_a.push(aVal);
                stack1_b.push(m-1);

                output.push(m);

                stack1_a.push(m+1);
                stack1_b.push(bVal);

            }
        }
        while(!output.isEmpty()) {
            System.out.println(output.pop());
        }
    }

这个输出:

(a, b) = (0, 3)
Recursive: 
0
1
2
3
Stack Implementation: 
0
3
2
1

【问题讨论】:

  • "我尝试循环遍历一个堆栈,每次弹出一个值 (a, b) 并压入一个新值 (a, m-1) 或 (m+1, b)而不是调用“fnc1()”,但输出总是乱序的。” 告诉我们,这样我们就可以帮助你理解为什么它乱序了。

标签: java recursion


【解决方案1】:

要正确实现此递归,您需要了解执行发生的顺序,然后以相反的顺序插入变量(因为堆栈弹出最新元素):

用 cmets 检查下面的代码:

public static void Fnc3S(int a, int b) {
    Stack<Integer> stack = new Stack<>(); // single stack for both input variables
    Stack<Integer> output = new Stack<>(); // single stack for output variable

    stack.push(a); // push original input
    stack.push(b);

    do {
        int bVal = stack.pop();
        int aVal = stack.pop();

        if (aVal <= bVal) {
            int m = (aVal + bVal) / 2;
            output.push(m); // push output

            stack.push(m + 1); // start with 2nd call to original function, remember - reverse order
            stack.push(bVal);

            stack.push(aVal); // push variables used for 1st call to original function
            stack.push(m - 1);
        } else {
            if (!output.empty()) { // original function just returns here to caller, so we should print any previously calculated outcome
                System.out.println(output.pop());
            }
        }
    } while (!stack.empty());
}

【讨论】:

    猜你喜欢
    • 2020-08-27
    • 1970-01-01
    • 2018-10-03
    • 2023-03-27
    • 2014-03-14
    • 2020-07-21
    • 2019-09-30
    • 2011-03-24
    • 2018-05-28
    相关资源
    最近更新 更多