关于go:GO-实现优先队列

2次阅读

共计 1244 个字符,预计需要花费 4 分钟才能阅读完成。

在 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)
    }
}

更多代码 点击这里

参考:

  • https://segmentfault.com/a/11…
正文完
 0