From 5b692968a99d98c7dd5a54af7015f5a9e0d06d19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=98=93=E6=98=A5=E9=A3=8E?= <77157236+night-cruise@users.noreply.github.com> Date: Fri, 29 Sep 2023 12:17:05 +0800 Subject: [PATCH] feat: add for-loop-recur rust codes (#803) --- .../recursion.rs | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/codes/rust/chapter_computational_complexity/recursion.rs b/codes/rust/chapter_computational_complexity/recursion.rs index d8c2a8d7f..9f4826bcd 100644 --- a/codes/rust/chapter_computational_complexity/recursion.rs +++ b/codes/rust/chapter_computational_complexity/recursion.rs @@ -17,6 +17,25 @@ fn recur(n: i32) -> i32 { n + res } +/* 使用迭代模拟递归 */ +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 +} + /* 尾递归 */ fn tail_recur(n: i32, res: i32) -> i32 { // 终止条件 @@ -47,6 +66,9 @@ fn main() { res = recur(n); println!("\n递归函数的求和结果 res = {res}"); + res = for_loop_recur(n); + println!("\n使用迭代模拟递归求和结果 res = {res}"); + res = tail_recur(n, 0); println!("\n尾递归函数的求和结果 res = {res}");