I have an assignment where I am given recursive functions, and have to rewrite it using only stacks (no recursion). I do not know how to implement the following function
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);
}
}
The problem is I cannot figure out how to implement recursive functions where there is head and tail recursion.
I tried to loop through a stack, popping a value (a, b) each time and pushing a new value (a, m-1) or (m+1, b) instead of caling "fnc1()", but the output was always out of order.
EDIT: Here is my attempted Code:
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());
}
}
And this outputs:
(a, b) = (0, 3)
Recursive:
0
1
2
3
Stack Implementation:
0
3
2
1
to implement this recursion properly you need to understand order in which execution happens and then insert variables in reverse order (as stack pops latest element):
Check code below with comments:
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());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.