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)