gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:06:55 24 4
gpt4 key购买 nike

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

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

最佳答案

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

检查下面的代码和注释:

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());
}

关于java - 如何仅使用堆栈实现递归函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60130001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com