如何用堆栈数据结构替换递归功能调用

How to replace a recursive function call with a stack data structure?

本文关键字:递归 功能 调用 替换 数据结构 何用 堆栈      更新时间:2023-10-16

我的递归称为函数:

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
     }
 }