一个由数组列表支持的二进制堆
type Iterator
func (iterator *Iterator) Begin() // 将迭代器重置为初始状态,然后调用Next获取第一个元素
func (iterator *Iterator) End() // 将迭代器移过最后一个元素,然后调用Prev获取最后一个元素
// 将迭代器移动到第一个元素,如果容器中有第一个元素则返回true。
// 如果First()返回true,则可以通过index()和value()检索第一个元素的索引和值。修改迭代器的状态
func (iterator *Iterator) First() bool
// 将迭代器移动到最后元素,如果容器中有第一个元素则返回true。
// 如果Last()返回true,则可以通过index()和value()检索第一个元素的索引和值。修改迭代器的状态
func (iterator *Iterator) Last() bool
func (iterator *Iterator) Next() bool
func (iterator *Iterator) Prev() bool
func (iterator *Iterator) Index() int
func (iterator *Iterator) Value() interface{}
type Iterator
func NewWith(comparator utils.Comparator) *Heap
// 用IntComparator实例化一个新的空堆,即元素的类型是int
func NewWithIntComparator() *Heap
// 用StringComparator实例化一个新的空堆,即元素的类型是String
func NewWithStringComparator() *Heap
func (heap *Heap) Clear()
func (heap *Heap) Empty() bool
func (heap *Heap) FromJSON(data []byte) error
func (heap *Heap) Iterator() Iterator
func (heap *Heap) Peek() (value interface{}, ok bool)
func (heap *Heap) Pop() (value interface{}, ok bool)
func (heap *Heap) Push(values ...interface{})
func (heap *Heap) Size() int
func (heap *Heap) String() string
func (heap *Heap) ToJSON() ([]byte, error)
func (heap *Heap) Values() []interface{}
例子:
package main
import (
"github.com/emirpasic/gods/trees/binaryheap"
"github.com/emirpasic/gods/utils"
)
// BinaryHeapExample to demonstrate basic usage of BinaryHeap
func main() {
// Min-heap
heap := binaryheap.NewWithIntComparator() // empty (min-heap)
heap.Push(2) // 2
heap.Push(3) // 2, 3
heap.Push(1) // 1, 3, 2
heap.Values() // 1, 3, 2
_, _ = heap.Peek() // 1,true
_, _ = heap.Pop() // 1, true
_, _ = heap.Pop() // 2, true
_, _ = heap.Pop() // 3, true
_, _ = heap.Pop() // nil, false (nothing to pop)
heap.Push(1) // 1
heap.Clear() // empty
heap.Empty() // true
heap.Size() // 0
// Max-heap
inverseIntComparator := func(a, b interface{}) int {
return -utils.IntComparator(a, b)
}
heap = binaryheap.NewWith(inverseIntComparator) // empty (min-heap)
heap.Push(2) // 2
heap.Push(3) // 3, 2
heap.Push(1) // 3, 2, 1
heap.Values() // 3, 2, 1
}