Documentation ¶
Overview ¶
Package priority_queue implements Priority Queue with four methods 1. Push(V). 2. Top() (V, error). 3. Pop() (V, error) 4. Size() int.
Usage pq, err := NewPriorityQueue(func(v1, v2 int){return v1<v2}) pq.Push(10) v, _ := pq.Top() v, _ = pq.Pop()
See more usage example in the priority_queue_test.go.
Why implement priority queue? The container/heap is not easy and intuitive to use because: 1. It requires boilerplate code to implement the heap interface. 2. Push/pop operations need to use heap.Push and heap.Pop on an array, which is not intuitive.
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ErrQueueIsEmpty = errors.New("queue is empty")
Functions ¶
This section is empty.
Types ¶
type PriorityQueue ¶
type PriorityQueue[V any] struct { // contains filtered or unexported fields }
PriorityQueue implements priority queue on any type as long as there is a less function to tell the "less-than" relationship between values of the type.
func NewPriorityQueue ¶
func NewPriorityQueue[V any](less func(v1, v2 V) bool) (*PriorityQueue[V], error)
NewPriorityQueue returns a priority queue. Returns error when the less function is nil.
func (*PriorityQueue[V]) Pop ¶
func (pq *PriorityQueue[V]) Pop() (V, error)
Pop removes and returns the smallest value if the queue is not empty.
func (*PriorityQueue[V]) Push ¶
func (pq *PriorityQueue[V]) Push(v V)
Push inserts a value to the priority queue.
func (*PriorityQueue[V]) Size ¶
func (pq *PriorityQueue[V]) Size() int
Size returns the number of values in the queue.
func (*PriorityQueue[V]) Top ¶
func (pq *PriorityQueue[V]) Top() (V, error)
Top returns the smallest value if the queue is not empty.