前言
C++、java等语言都实现了栈、堆、队列、优先级队列等。但是Go语言却没有。我们在实际使用中却是需要这些基础数据结构,怎么办?自己造!
heap && priority_queue
go语言有标准容器库 “container/heap”,我们可以根据这个库来实现堆以及优先级队列:
先看 “container/heap” 里的定义:
type Interface interface {
sort.Interface
Push(x interface{
}) // add x as element Len()
Pop() interface{
} // remove and return element Len() - 1.
}
这个堆使用的数据结构是最小二叉树,即根节点比左边子树和右边子树的所有值都小,其中 sort.Interface的定义如下:
type Interface interface {
// Len is the number of elements in the collection.
Len() int
// Less reports whether the element with
// index i should sort before the element with index j.
Less(i, j int) bool
// Swap swaps the elements with indexes i and j.
Swap(i, j int)
}
所以要实现这五个接口就可以了~,话不多说,开干!
实现堆
// intHeap 实现了 heap 的接口
package kit
import (
"container/heap"
)
type intHeap []int
func (h intHeap) Len() int {
return len(h)
}
func (h intHeap) Less(i, j int) bool {
return h[i] < h[j]
}
func (h intHeap) Swap(i, j int) {
h[i], h[j] = h[j], h[i