先放一个入门版
package main
import (
"container/heap"
"fmt"
)
type Elem struct {
Value int // 数据
Priority int // 优先级
Index int // 位置
}
type PriorityQueue []*Elem
func (pq PriorityQueue) Len() int {
return len(pq)
}
func (pq PriorityQueue) Less(i int, j int) bool {
return pq[i].Priority < pq[j].Priority
}
func (pq PriorityQueue) Swap(i int, j int) {
pq[i], pq[j] = pq[j], pq[i]
pq[i].Index, pq[j].Index = pq[j].Index, pq[i].Index
}
func (pq *PriorityQueue) Pop() interface{} {
old := *pq
lenOfOld := len(old)
item := old[ lenOfOld-1 ]
*pq = old[0 : lenOfOld-1]
item.Index = -1
return item
}
func (pq *PriorityQueue) Push(x interface{}) {
n := len(*pq)
item := x.(*Elem)
item.Index = n
*pq = append(*pq, item)
}
func (pq *PriorityQueue) update(item *Elem, value int, priority int) {
item.Value = value
item.Priority = priority
heap.Fix(pq, item.Index)
}
func main() {
items := [...]int{5, 3, 9}
i := 0
pq := make(PriorityQueue, len(items)) // 创建优先级队列,并初始化
for _, k := range items { // 将节点放到优先级队列中
pq[i] = &Elem{
Value: k,
Priority: k,
Index: i}
i++
}
heap.Init(&pq) // 初始化堆
item := &Elem{ // 创建一个item
Value: 10,
Priority: 10,
}
heap.Push(&pq, item) // 入优先级队列
pq.update(item, item.Value, 6) // 更新item的优先级
for len(pq) > 0 {
item := heap.Pop(&pq).(*Elem)
fmt.Printf("%d:%d index:%d\n", item.Priority, item.Value, item.Index)
}
}