golang基于heap库实现简易优先队列


本文摘自网络,作者,侵删。

优先队列在C++/Java等语言中已经存在于标准库中,而go语言中却没有。今天用了下,留个纪念吧

package main
import (
    "container/heap"
    "fmt"
)

type IntHeap []int

func (h IntHeap) Len() int           { return len(h) }
func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] }     // 大顶堆,返回值决定是否交换元素
func (h IntHeap) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }

func (h *IntHeap) Push(x interface{}) {
    *h = append(*h, x.(int))
}

func (h *IntHeap) Pop() interface{} {
    old := *h
    n := len(old)
    x := old[n-1]
    *h = old[0 : n-1]
    return x
}

func TestIntHeap(t *testing.T) {
    pq := &IntHeap{}
    heap.Init(pq)
    for i := 1; i < 10; i++ {
        heap.Push(pq, i)
    }

    for len(*pq) > 0 {
        x := heap.Pop(pq)
        fmt.Println(x)
    }
}

/*
输出结果
1
2
3
4
5
6
7
8
9
*/

本文来自:简书

感谢作者:克罗地亚催眠曲

查看原文:golang基于heap库实现简易优先队列

相关阅读 >>

Go指针

emacs支持Golang吗

Go - time.rfc3339 时间格式化

dbatool-dodba

skywalking Golang客户端源码解析

Go语言中的不定参数类型是什么意思

Go 读写锁实现原理解读

手撸Golang Go与微服务 net.rpc

学习Go语言(Golang)编译过程预备知识

markdown 自定义的思考

更多相关阅读请进入《Go》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...