diff --git a/codes/c/chapter_computational_complexity/recursion.c b/codes/c/chapter_computational_complexity/recursion.c index adf3db4707..8241e3bfc0 100644 --- a/codes/c/chapter_computational_complexity/recursion.c +++ b/codes/c/chapter_computational_complexity/recursion.c @@ -17,6 +17,25 @@ int recur(int n) { return n + res; } +/* 使用迭代模拟递归 */ +int forLoopRecur(int n) { + int stack[1000]; // 借助一个大数组来模拟栈 + int top = 0; + int res = 0; + // 递:递归调用 + for (int i = n; i > 0; i--) { + // 通过“入栈操作”模拟“递” + stack[top++] = i; + } + // 归:返回结果 + while (top >= 0) { + // 通过“出栈操作”模拟“归” + res += stack[top--]; + } + // res = 1+2+3+...+n + return res; +} + /* 尾递归 */ int tailRecur(int n, int res) { // 终止条件