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库实现简易优先队列

相关阅读 >>

手撸Golang 行为型设计模式 命令模式

Golang elasticsearch7的使用

3.树莓派常用软件&篇程语言&篇程环境(32位/64位)

Go语言并不简单

[译] 使用 Go 语言编写一个简单的 shell

Go语言happens-before原则及应用

[系列] Go - 学习 grpc.dial(target string, opts …dialoption) 的写法

分享一款Golang style语法的Golang orm库

[Go]使用Go-smtp发送邮件通知

Go cassandra 示例2

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




打赏

取消

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

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

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

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

评论

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