This commit is contained in:
krahets
2023-09-29 21:43:04 +08:00
parent c10c457827
commit 543ecebfd0
4 changed files with 35 additions and 13 deletions

View File

@@ -1591,7 +1591,24 @@ status: new
=== "Rust"
```rust title="recursion.rs"
[class]{}-[func]{for_loop_recur}
/* 使用迭代模拟递归 */
fn for_loop_recur(n: i32) -> i32 {
// 使用一个显式的栈来模拟系统调用栈
let mut stack = Vec::new();
let mut res = 0;
// 递:递归调用
for i in (1..=n).rev() {
// 通过“入栈操作”模拟“递”
stack.push(i);
}
// 归:返回结果
while !stack.is_empty() {
// 通过“出栈操作”模拟“归”
res += stack.pop().unwrap();
}
// res = 1+2+3+...+n
res
}
```
=== "C"