You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
39 lines
1.1 KiB
Go
39 lines
1.1 KiB
Go
package container
|
|
|
|
import (
|
|
"golang.org/x/exp/constraints"
|
|
)
|
|
|
|
// PriorityQueue represents a priority queue data structure.
|
|
type PriorityQueue[T any, V constraints.Integer] struct {
|
|
heap *Heap[T, V]
|
|
}
|
|
|
|
// NewPriorityQueue creates a new PriorityQueue instance.
|
|
// isMinQueue determines whether it is a min-priority queue (true) or a max-priority queue (false).
|
|
func NewPriorityQueue[T any, V constraints.Integer](isMinQueue bool) *PriorityQueue[T, V] {
|
|
return &PriorityQueue[T, V]{
|
|
heap: NewHeap[T, V](isMinQueue),
|
|
}
|
|
}
|
|
|
|
// Enqueue adds an element to the priority queue.
|
|
func (pq *PriorityQueue[T, V]) Enqueue(element T, priority V) {
|
|
pq.heap.Push(element, priority)
|
|
}
|
|
|
|
// Dequeue removes and returns the element with the highest priority from the queue.
|
|
func (pq *PriorityQueue[T, V]) Dequeue() T {
|
|
return pq.heap.Pop()
|
|
}
|
|
|
|
// Peek returns the element with the highest priority without removing it from the queue.
|
|
func (pq *PriorityQueue[T, V]) Peek() T {
|
|
return pq.heap.Peek()
|
|
}
|
|
|
|
// IsEmpty returns true if the priority queue is empty.
|
|
func (pq *PriorityQueue[T, V]) IsEmpty() bool {
|
|
return len(pq.heap.elements) == 0
|
|
}
|