Add Go codes to docs, including

the chapter of stack and queue, the chapter of tree.
This commit is contained in:
Yudong Jin
2022-12-03 20:25:24 +08:00
parent 1d9a076cdd
commit ebf9024136
41 changed files with 898 additions and 486 deletions

View File

@@ -4,65 +4,105 @@
package chapter_stack_and_queue
import "testing"
import (
"fmt"
"testing"
. "github.com/krahets/hello-algo/pkg"
)
func TestStack(t *testing.T) {
/* 初始化栈 */
// 在 Go 中,推荐将 Slice 当作栈来使用
var stack []int
/* 元素入栈 */
stack = append(stack, 1)
stack = append(stack, 3)
stack = append(stack, 2)
stack = append(stack, 5)
stack = append(stack, 4)
fmt.Print("栈 = ")
PrintSlice(stack)
/* 访问栈顶元素 */
peek := stack[len(stack)-1]
fmt.Println("栈顶元素 peek =", peek)
/* 元素出栈 */
pop := stack[len(stack)-1]
stack = stack[:len(stack)-1]
fmt.Print("出栈元素 pop = ", pop, ",出栈后 stack = ")
PrintSlice(stack)
/* 获取栈的长度 */
size := len(stack)
fmt.Println("栈的长度 size =", size)
/* 判断是否为空 */
isEmpty := len(stack) == 0
fmt.Println("栈是否为空 =", isEmpty)
}
func TestArrayStack(t *testing.T) {
// 初始化栈, 使用接口承接
var stack Stack
stack = NewArrayStack()
stack := NewArrayStack()
// 元素入栈
stack.Push(1)
stack.Push(2)
stack.Push(3)
stack.Push(4)
stack.Push(2)
stack.Push(5)
t.Log("栈 stack = ", stack.toString())
stack.Push(4)
fmt.Print("栈 stack = ")
PrintSlice(stack.toSlice())
// 访问栈顶元素
peek := stack.Peek()
t.Log("栈顶元素 peek = ", peek)
fmt.Println("栈顶元素 peek =", peek)
// 元素出栈
pop := stack.Pop()
t.Log("出栈元素 pop = ", pop, ", 出栈后 stack =", stack.toString())
fmt.Print("出栈元素 pop = ", pop, ", 出栈后 stack = ")
PrintSlice(stack.toSlice())
// 获取栈的长度
size := stack.Size()
t.Log("栈的长度 size = ", size)
fmt.Println("栈的长度 size =", size)
// 判断是否为空
isEmpty := stack.IsEmpty()
t.Log("栈是否为空 = ", isEmpty)
fmt.Println("栈是否为空 =", isEmpty)
}
func TestLinkedListStack(t *testing.T) {
// 初始化栈
var stack Stack
stack = NewLinkedListStack()
stack := NewLinkedListStack()
// 元素入栈
stack.Push(1)
stack.Push(2)
stack.Push(3)
stack.Push(4)
stack.Push(2)
stack.Push(5)
t.Log("栈 stack = ", stack.toString())
stack.Push(4)
fmt.Print("栈 stack = ")
PrintList(stack.toList())
// 访问栈顶元素
peek := stack.Peek()
t.Log("栈顶元素 peek = ", peek)
fmt.Println("栈顶元素 peek =", peek)
// 元素出栈
pop := stack.Pop()
t.Log("出栈元素 pop = ", pop, ", 出栈后 stack =", stack.toString())
fmt.Print("出栈元素 pop = ", pop, ", 出栈后 stack = ")
PrintList(stack.toList())
// 获取栈的长度
size := stack.Size()
t.Log("栈的长度 size = ", size)
fmt.Println("栈的长度 size =", size)
// 判断是否为空
isEmpty := stack.IsEmpty()
t.Log("栈是否为空 = ", isEmpty)
fmt.Println("栈是否为空 =", isEmpty)
}
// BenchmarkArrayStack 8 ns/op in Mac M1 Pro