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,12 +4,54 @@
package chapter_stack_and_queue
import "testing"
import (
"container/list"
"fmt"
"testing"
. "github.com/krahets/hello-algo/pkg"
)
func TestDeque(t *testing.T) {
/* 初始化双向队列 */
// 在 Go 中,将 list 作为双向队列使用
deque := list.New()
/* 元素入队 */
deque.PushBack(2)
deque.PushBack(5)
deque.PushBack(4)
deque.PushFront(3)
deque.PushFront(1)
fmt.Print("双向队列 deque = ")
PrintList(deque)
/* 访问元素 */
front := deque.Front()
fmt.Println("队首元素 front =", front.Value)
rear := deque.Back()
fmt.Println("队尾元素 rear =", rear.Value)
/* 元素出队 */
deque.Remove(front)
fmt.Print("队首出队元素 front = ", front.Value, ",队首出队后 deque = ")
PrintList(deque)
deque.Remove(rear)
fmt.Print("队尾出队元素 rear = ", rear.Value, ",队尾出队后 deque = ")
PrintList(deque)
/* 获取双向队列的长度 */
size := deque.Len()
fmt.Println("双向队列长度 size =", size)
/* 判断双向队列是否为空 */
isEmpty := deque.Len() == 0
fmt.Println("双向队列是否为空 =", isEmpty)
}
func TestLinkedListDeque(t *testing.T) {
// 初始化队列
var deque Deque
deque = NewLinkedListDeque()
deque := NewLinkedListDeque()
// 元素入队
deque.OfferLast(2)
@@ -17,27 +59,30 @@ func TestLinkedListDeque(t *testing.T) {
deque.OfferLast(4)
deque.OfferFirst(3)
deque.OfferFirst(1)
t.Log("队列 deque = ", deque.toString())
fmt.Print("队列 deque = ")
PrintList(deque.toList())
// 访问队首元素
peekFirst := deque.PeekFirst()
t.Log("队首元素 peek = ", peekFirst)
peekLast := deque.PeekLast()
t.Log("队尾元素 peek = ", peekLast)
front := deque.PeekFirst()
fmt.Println("队首元素 front =", front)
rear := deque.PeekLast()
fmt.Println("队尾元素 rear =", rear)
// 元素出队
pollFirst := deque.PollFirst()
t.Log("队首出队元素 pollFirst = ", pollFirst, ",队首出队后 deque = ", deque.toString())
fmt.Print("队首出队元素 pollFirst = ", pollFirst, ",队首出队后 deque = ")
PrintList(deque.toList())
pollLast := deque.PollLast()
t.Log("队尾出队元素 pollLast = ", pollLast, ",队尾出队后 deque = ", deque.toString())
fmt.Print("队尾出队元素 pollLast = ", pollLast, ",队尾出队后 deque = ")
PrintList(deque.toList())
// 获取队的长度
size := deque.Size()
t.Log("队的长度 size = ", size)
fmt.Println("队的长度 size =", size)
// 判断是否为空
isEmpty := deque.IsEmpty()
t.Log("队是否为空 = ", isEmpty)
fmt.Println("队是否为空 =", isEmpty)
}
// BenchmarkArrayQueue 67.92 ns/op in Mac M1 Pro