pq

package module
v0.0.0-...-401dc3f Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 24, 2025 License: MIT Imports: 2 Imported by: 0

README

pq

一个基于 Go 泛型实现的 优先队列 (Priority Queue),支持大顶堆和小顶堆模式。

Go Reference


📦 安装

go get github.com/emove/pq

🚀 快速开始

package main

import (
    "fmt"
    "github.com/Emove/pq"
)

func main() {
    // 创建一个小顶堆(默认)
    q := pq.New[int]()
	// 创建一个大顶堆
	// q := pq.New[int](pq.MaxHeap()) 

    // 插入元素
    q.Insert(10, 3.0)
    q.Insert(20, 1.0)
    q.Insert(30, 2.0)

    fmt.Println("队列长度:", q.Len()) // 3

    // 弹出优先级最高(最小值)的元素
    v, _ := q.Pop()
    fmt.Println("Pop:", v) // 输出 20,因为它的 priority=1.0 最小

    // 更新某个元素的优先级
    q.UpdatePriority(30, 0.5)

    v, _ = q.Pop()
    fmt.Println("Pop:", v) // 输出 30,因为更新后 priority=0.5
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type PriorityQueue

type PriorityQueue[T any] struct {
	// contains filtered or unexported fields
}

PriorityQueue represents the queue

func New

func New[T any](ops ...PriorityQueueOption) PriorityQueue[T]

New initializes an empty priority queue.

func (*PriorityQueue[T]) Insert

func (p *PriorityQueue[T]) Insert(v T, priority float64)

Insert inserts a new element into the queue. No action is performed on duplicate elements.

func (*PriorityQueue[T]) Len

func (p *PriorityQueue[T]) Len() int

Len returns the number of elements in the queue.

func (*PriorityQueue[T]) Pop

func (p *PriorityQueue[T]) Pop() (T, error)

Pop removes the element with the highest priority from the queue and returns it. In case of an empty queue, an error is returned.

func (*PriorityQueue[T]) UpdatePriority

func (p *PriorityQueue[T]) UpdatePriority(x T, newPriority float64)

UpdatePriority changes the priority of a given item. If the specified item is not present in the queue, no action is performed.

type PriorityQueueOption

type PriorityQueueOption func(*option)

func MaxHeap

func MaxHeap() PriorityQueueOption

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL