add forLoopRecur in recursion.c (#866)
This commit is contained in:
parent
faa44fecd2
commit
ea7275ab6a
@ -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) {
|
||||
// 终止条件
|
||||
|
Loading…
x
Reference in New Issue
Block a user