From 61e1d1faec2c35e64f52de134b663d0a196cdac2 Mon Sep 17 00:00:00 2001 From: Nepenthe <121146765+theNefelibatas@users.noreply.github.com> Date: Sat, 7 Oct 2023 21:47:58 +0800 Subject: [PATCH] feat(go): add forLoopRecur func (#816) --- .../recursion.go | 22 +++++++++++++++++++ .../recursion_test.go | 3 +++ 2 files changed, 25 insertions(+) diff --git a/codes/go/chapter_computational_complexity/recursion.go b/codes/go/chapter_computational_complexity/recursion.go index 143065016..8dd5cd980 100644 --- a/codes/go/chapter_computational_complexity/recursion.go +++ b/codes/go/chapter_computational_complexity/recursion.go @@ -4,6 +4,8 @@ package chapter_computational_complexity +import "container/list" + /* 递归 */ func recur(n int) int { // 终止条件 @@ -16,6 +18,26 @@ func recur(n int) int { return n + res } +/* 使用迭代模拟递归 */ +func forLoopRecur(n int) int { + // 使用一个显式的栈来模拟系统调用栈 + stack := list.New() + res := 0 + // 递:递归调用 + for i := n; i > 0; i-- { + // 通过“入栈操作”模拟“递” + stack.PushBack(i) + } + // 归:返回结果 + for stack.Len() != 0 { + // 通过“出栈操作”模拟“归” + res += stack.Back().Value.(int) + stack.Remove(stack.Back()) + } + // res = 1+2+3+...+n + return res +} + /* 尾递归 */ func tailRecur(n int, res int) int { // 终止条件 diff --git a/codes/go/chapter_computational_complexity/recursion_test.go b/codes/go/chapter_computational_complexity/recursion_test.go index 675035559..40ad75365 100644 --- a/codes/go/chapter_computational_complexity/recursion_test.go +++ b/codes/go/chapter_computational_complexity/recursion_test.go @@ -15,6 +15,9 @@ func TestRecursion(t *testing.T) { res := recur(n) fmt.Println("\n递归函数的求和结果 res = ", res) + res = forLoopRecur(n) + fmt.Println("\n使用迭代模拟递归求和结果 res = ", res) + res = tailRecur(n, 0) fmt.Println("\n尾递归函数的求和结果 res = ", res)