add forLoopRecur in recursion.c (#866)

This commit is contained in:
Yudong Jin 2023-10-17 07:28:17 -05:00 committed by GitHub
parent faa44fecd2
commit ea7275ab6a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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) {
// 终止条件