GO 实现优先队列

在php中提供了SplPriorityQueue来实现优先队列操作。在Go中,虽然没有直接提供优先队列的实现,不过通过标准库container/heap可以很方便的实现一个简单的优先队列。

heap 提供了堆的数据结构,通过实现heap.Interface接口,可以快速实现最大堆或者最小堆。而优先队列通常是在最大堆上做封装即可。在go官网heap包的文档中,提供了一个简单的优先队列演示,以下基于go官方文档中的代码做重新调整实现优先队,用go实现了php优先队列代码中的演示。

package main

import (
    "container/heap"
    "fmt"
)

type Item struct {
    value    string // The value of the item; arbitrary.
    priority int    // The priority of the item in the queue.
}

type PriorityQueue []*Item

func (pq PriorityQueue) Len() int { return len(pq) }
func (pq PriorityQueue) Less(i, j int) bool {
    return pq[i].priority > pq[j].priority
}

func (pq PriorityQueue) Swap(i, j int) {
    pq[i], pq[j] = pq[j], pq[i]
}

func (pq *PriorityQueue) Push(x interface{}) {
    item := x.(*Item)
    *pq = append(*pq, item)
}

func (pq *PriorityQueue) Pop() interface{} {
    old := *pq
    n := len(old)
    item := old[n-1]
    old[n-1] = nil
    *pq = old[0 : n-1]
    return item
}

func main() {
    queue := new(PriorityQueue)
    heap.Init(queue)

    heap.Push(queue, &Item{value: "A", priority: 3})
    heap.Push(queue, &Item{value: "B", priority: 6})
    heap.Push(queue, &Item{value: "C", priority: 1})
    heap.Push(queue, &Item{value: "D", priority: 2})

    len := queue.Len()
    fmt.Println("优先队列长度:", len)

    item := (*queue)[0]
    fmt.Println("top 提取值: ", item.value)
    fmt.Println("top 提取优先级: ", item.priority)

    fmt.Println("遍历")
    for queue.Len() > 0 {
        fmt.Println(heap.Pop(queue).(*Item).value)
    }
}

更多代码 点击这里

参考:

你可能感兴趣的:(go优先队列)