利用栈将递归转换为非递归
对于一般的递归过程,仿照递归算法执行过程中递归工作栈的状态变化,可直接写出相应的非递归算法。
步骤
第一次调用的参数push进堆栈,原有递归代码外层加一个while循环,判断条件就是递归结束的条件。递归调用的地方改成push(); continue;
直到遇到递归终止条件,退出递归运算所在循环,再用一个新的循环做出栈操作并计算,将递归代码中的return改成pop并执行响应的计算,直到栈空为止。就可以了。
完整描述:
(1) 设置一个工作栈存放递归工作记录(包括实参、 返回地址及局部变量等)。
(2) 进入非递归调用入口(即被调用程序开始处) 将调用程序传来的实参和返回地址入栈(递归程序不可以作为主程序,因而可认为初始是被某个调用程序调用。
(3) 进入递归调用入口:当不满足递归结束条件时,逐层递归,将实参、 返回地址及局部变量入栈,这一过程可用循环语句来实现一模拟递归分解的过程。
(4) 递归结束条件满足,将到达递归出口的给定常数作为当前的函数值。
(5) 返回处理:在栈不空的情况下,反复退出栈顶记录,根据记录中的返回地址进行题意规定的操作,即逐层计算当前函数值,直至栈空为止一模拟递归求值过程。
通过以上步骤,可将任何递归算法改写成非递归算法。但改写后的非递归算法和原来比较起来,结构不够清晰,可读性差,有的还需要经过一系列的优化。
代码示例
设 n 为大于等于 0 的整数,利用堆栈设计下列函数的非递归算法。(天津大学,2006)
下面将给出一种递归解法、四种非递归解法,供参考。
import java.util.Stack;
public class Recursion {
public static void main(String[] args) {
// 测试用例
for (int i = 0; i < 20; i++) {
System.out.println(recursion(i));
System.out.println(non_recursion1(i));
System.out.println(non_recursion2(i));
System.out.println(non_recursion3(i));
System.out.println(non_recursion4(i));
System.out.println("=====");
}
}
/**
* 使用递归
*/
public static int recursion(int n) {
if (n == 0) {
return 1;
} else {
int b = n / 2;
int res = recursion(b);
return n * res;
}
}
/**
* 非递归方法1:利用栈,双参数
*/
public static int non_recursion1(int n) {
class Node {
int a;
int b;
}
Stack<Node> stack = new Stack<>();
int result = 1;
if (n < 0) return 0;
if (n == 0) return 1;
else {
while (n != 0) {
Node node = new Node();
node.a = n;
node.b = n / 2;
n = node.b;
stack.push(node);
}
while (!stack.isEmpty()) {
result = result * stack.pop().a;
}
}
return result;
}
/**
* (推荐解法)非递归方法2:利用栈,单参数
*/
public static int non_recursion2(int n) {
Stack<Integer> stack = new Stack<>();
int result = 1;
if (n < 0) return 0;
if (n == 0) return 1;
else {
while (n != 0) {
stack.push(n);
n = n / 2;
}
while (!stack.isEmpty()) {
result = result * stack.pop();
}
}
return result;
}
/**
* 非递归方法3:自定义数组模拟栈,双参数
*/
public static int non_recursion3(int n) {
class Node {
int a;
int b;
}
Node[] node = new Node[100];
int result = 1;
int top = 0;
if (n < 0) return 0;
if (n == 0) result = 1;
else {
while (n != 0) {
top++;
node[top] = new Node();
node[top].a = n;
node[top].b = n / 2;
n = node[top].b;
}
while (top != 0) {
result = result * node[top--].a;
}
}
return result;
}
/**
* 由于是尾递归,因此可以不用栈
*/
public static int non_recursion4(int n) {
int result = 1;
if (n < 0) return 0;
if (n == 0) return 1;
else {
while (n != 0) {
result = result * n;
n = n / 2;
}
return result;
}
}
}