如何仅使用堆栈来实现递归函数?

问题描述 投票:1回答:1

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

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
java recursion
1个回答
0
投票

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

检查下面带有注释的代码:

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());
}
© www.soinside.com 2019 - 2024. All rights reserved.