在一般情况下,如果您想将递归替换为平面代码,您应该使用堆栈(LIFO)。所以如果你有递归算法:
void print(std::string str, int depth)
{
if (depth == n) {
std::cout << str << std::endl;
return;
}
for (int i = 0; i < 10; ++i) {
char val[2] = { i + '0', 0 };
print(str + val + ", ", depth+1);
}
}
您可以通过保存局部变量(在本例中为 str 和 i)将其转换为基于 LIFO 的:
struct StackItem {
StackItem(const std::string& ss, unsigned ii)
: str(ss), i(ii)
{}
std::string str;
int i;
};
void print_norec()
{
std::list< StackItem > stack;
stack.push_back(StackItem("", 0));
while (!stack.empty()) {
StackItem& current = stack.back();
if (stack.size() == n+1) {
std::cout << current.str << std::endl;
stack.pop_back(); // return from "recursive" function
continue;
}
if (current.i < 10) {
char val[2] = { current.i + '0', 0 };
// call "recursive" function
stack.push_back(StackItem(current.str + val + ", ", 0));
current.i++;
} else {
stack.pop_back(); // return from "recursive" function
}
}
}