栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

优先队列和堆

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

优先队列和堆

如示例代码所示,该

Push
方法必须具有指针接收器。

诀窍是所有对

heap.XXX
函数的调用都要求您将堆作为指针传递(例如:)
heap.Init(&pq)
。在您发布的代码中情况并非如此。这是您的代码的有效版本。您可以在Go操场上运行它。

请注意,在这段代码中,我明确地将队列初始化为指针:

q := new(PriorityQueue)
。这就是我传递给所有
heap
功能的东西。

之所以引起这种混乱,主要是因为您实际上要实现2个接口。的

heap.Interface
sort.Interface
(后者是现有的类型定义的一部分)。但是sort接口对于非指针接收器来说是很好的,而另一个接口则不是。

package mainimport "fmt"import "container/heap"func main() {    q := new(PriorityQueue)    heap.Init(q)    fmt.Printf("nAdr: %pn", &q)    q.Push(NewItem("h", 2))    for i := 0; i < 5; i++ {        heap.Push(q, NewItem("test", i*13%7))    }    for q.Len() > 0 {        fmt.Println("Item: " + heap.Pop(q).(string))    }}type Item struct {    container interface{}    priority  int    index     int}type PriorityQueue []*Itemfunc NewItem(value interface{}, prio int) *Item {    return &Item{container: value, priority: prio}}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]    pq[i].index = i    pq[j].index = j}func (pq *PriorityQueue) Push(x interface{}) {    fmt.Printf("adr: %pn", pq)    n := len(*pq)    item := x.(*Item)    item.index = n    *pq = append(*pq, item)}func (pq *PriorityQueue) Pop() interface{} {    old := *pq    n := len(old)    itm := old[n-1]    itm.index = -1    *pq = old[0 : n-1]    return itm.container}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/406501.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号