mirror of
https://github.com/krahets/hello-algo.git
synced 2024-12-25 02:16:28 +08:00
feat(go): add forLoopRecur func (#816)
This commit is contained in:
parent
ef87bd494a
commit
61e1d1faec
2 changed files with 25 additions and 0 deletions
|
@ -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 {
|
||||
// 终止条件
|
||||
|
|
|
@ -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)
|
||||
|
||||
|
|
Loading…
Reference in a new issue