Skip to content

Commit

Permalink
add forLoopRecur in recursion.c (krahets#866)
Browse files Browse the repository at this point in the history
  • Loading branch information
krahets authored Oct 17, 2023
1 parent faa44fe commit ea7275a
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions codes/c/chapter_computational_complexity/recursion.c
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
// 终止条件
Expand Down

0 comments on commit ea7275a

Please sign in to comment.