109 字
1 分钟

优先级队列

2025-05-05
无标签
文章目录

优先级队列是一种基于二叉堆的数据结构。

优先级队列会使用到二叉堆二叉堆二叉堆 操作。

入队#

template<class T>
void Enqueue(T item, int priority)
{
heap.Add(new PriorityItem(item, priority));
ShiftUp(heap, heap.length, heap.length - 1);
}

出队#

template<class T>
T Dequeue()
{
if (heap.Count == 0)
throw new InvalidOperationException("Queue is empty");
T result = heap[0].Item;
// 将最后一个元素移到堆顶
heap[0] = heap[heap.Count - 1];
heap.RemoveAt(heap.Count - 1);
if (heap.Count > 0)
HeapifyDown(heap, heap.length, 0);
return result;
}