mirror of
https://github.com/krahets/hello-algo.git
synced 2026-04-27 20:11:01 +08:00
build
This commit is contained in:
@@ -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"
|
||||
|
||||
Reference in New Issue
Block a user