Go实现队列、栈、堆、优先级队列

前言

C++、java等语言都实现了栈、堆、队列、优先级队列等。但是Go语言却没有。我们在实际使用中却是需要这些基础数据结构,怎么办?自己造!

heap && priority_queue

go语言有标准容器库 “container/heap”,我们可以根据这个库来实现堆以及优先级队列:
先看 “container/heap” 里的定义:

type Interface interface {
   
    sort.Interface
    Push(x interface{
   }) // add x as element Len()
    Pop() interface{
   }   // remove and return element Len() - 1.
}

这个堆使用的数据结构是最小二叉树,即根节点比左边子树和右边子树的所有值都小,其中 sort.Interface的定义如下:

type Interface interface {
   
    // Len is the number of elements in the collection.
    Len() int
    // Less reports whether the element with
    // index i should sort before the element with index j.
    Less(i, j int) bool
    // Swap swaps the elements with indexes i and j.
    Swap(i, j int)
}

所以要实现这五个接口就可以了~,话不多说,开干!

实现堆

// intHeap 实现了 heap 的接口
package kit

import (
    "container/heap"
)

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
  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值