Skip to content

Commit

Permalink
fix(heap): add go codes
Browse files Browse the repository at this point in the history
  • Loading branch information
Reanon committed Jan 13, 2023
1 parent 3dcdd1c commit ec28b4c
Show file tree
Hide file tree
Showing 2 changed files with 1 addition and 41 deletions.
40 changes: 0 additions & 40 deletions codes/go/chapter_heap/heap.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,6 @@

package chapter_heap

import (
"container/heap"
"fmt"
)

// Go 语言中可以通过实现 heap.Interface 来构建整数大顶堆
// 实现 heap.Interface 需要同时实现 sort.Interface
type intHeap []any
Expand Down Expand Up @@ -48,38 +43,3 @@ func (h *intHeap) Swap(i, j int) {
func (h *intHeap) Top() any {
return (*h)[0]
}

/* Driver Code */
func main() {
/* 初始化堆 */
// 初始化大顶堆
maxHeap := &intHeap{}
heap.Init(maxHeap)
/* 元素入堆 */
// 调用 heap.Interface 的方法,来添加元素
heap.Push(maxHeap, 1)
heap.Push(maxHeap, 3)
heap.Push(maxHeap, 2)
heap.Push(maxHeap, 4)
heap.Push(maxHeap, 5)

/* 获取堆顶元素 */
top := maxHeap.Top()
fmt.Printf("堆顶元素为 %d\n", top)

/* 堆顶元素出堆 */
// 调用 heap.Interface 的方法,来移除元素
heap.Pop(maxHeap)
heap.Pop(maxHeap)
heap.Pop(maxHeap)
heap.Pop(maxHeap)
heap.Pop(maxHeap)

/* 获取堆大小 */
size := len(*maxHeap)
fmt.Printf("堆元素数量为 %d\n", size)

/* 判断堆是否为空 */
isEmpty := len(*maxHeap) == 0
fmt.Printf("堆是否为空 %t\n", isEmpty)
}
2 changes: 1 addition & 1 deletion docs/chapter_heap/heap.md
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ comments: true

```go title="my_heap.go"
type maxHeap struct {
// 使用切片而非数组,这样无需考虑扩容问题
// 使用切片而非数组,这样无需考虑扩容问题
data []any
}

Expand Down

0 comments on commit ec28b4c

Please sign in to comment.