如何用堆栈数据结构替换递归功能调用
How to replace a recursive function call with a stack data structure?
我的递归称为函数:
void func(int a, bool arr[]) {
...
if ( ... ) {
func(a, arr);
}
}
并从我的主代码中调用它,例如
int int_var = 0;
bool bool_array[10];
func(int_var, bool_array);
现在,我想使用堆栈数据结构来替换该功能的递归调用。
我该怎么做,例如使用std::stack
?
用循环和使用std::stack<>
替换递归调用非常简单。
函数调用使用程序/线程固有函数调用堆栈,因此该函数的递归调用只是意味着在堆栈上推动实际参数值。
函数返回后,结果就会确定并从堆栈中弹出。
给出一个更好适合的例子,我用std::vector<bool>
替换了您的bool[]
数组:
struct params {
int a;
std::vector<bool> arr;
};
std::stack<params> myStack;
int int_var = 0;
std::vector<bool> bool_array;
// put an initial value onto the stack
myStack.push(params{int_var,bool_array});
while(!myStack.empty()) {
// compute int_var and the bool_array
if(/* ... */) {
myStack.push(params{int_var,bool_array});
}
else {
params p = myStack.top();
myStack.pop();
// handle results of the previous computation
}
}
相关文章:
- 通过递归进行因子分解
- 我在 C++ 中创建了一个函数来递归反转字符串,但是之后如何使功能打印一个 endl?
- 如果我具有调用其其他实例之一的超载函数,它是否被认为是递归功能
- 编写一个递归功能,该功能采用数组并以相反顺序显示元素,而无需在末尾启动数组的索引
- 无全局变量或功能参数的递归调用
- 在递归功能中,我如何跳到堆栈上的其他功能调用
- ConstexPR模板功能的无限递归
- 在1个功能中打印相反的三角递归C
- 简单的二进制搜索树非递归添加功能
- C :重复的变化的递归功能,按不同字母数量排序
- 递归功能,以打印每个新位置以进行控制
- 避免此功能的递归
- 编译器无法在循环递归参考中找到功能
- 关于C (初学者级别)中的递归功能
- 通过递归模板中的参考传递模板功能
- 将这个糟糕但功能强大的代码转换为递归函数
- 用于列出子目录中所有文件的递归功能
- 编译时间递归函数以计算两个整数的下一个功能
- 通过使用递归功能
- 霍夫曼编码器-递归,编码功能失败