数据结构(七)优先级队列
优先级队列–c++实现
优先级队列的定义
优先级队列是0个或多个元素的集合,每个元素都有一个优先权或值,对优先级队列执行的操作有:
-
查找一个元素(top)
-
插入一个新元素(push)
-
删除一个元素(pop)
在最小优先级队列中,查找和删除的元素都是优先级最小的元素;在最大优先级队列中,查找和删除的元素都是优先级最大的元素。优先级队列的元素可以有相同的优先级,对这样的元素,查找和删除可以按任意顺序处理。
优先级队列的描述
在maxPriorityQueue.h文件中,定义了结构体node,声明了maxPriorityQueue类
template<class T> struct node{
T data;
node* next;
int point;
node(){}
node(T element,int p){
data = element;
next = nullptr;
point = p;
}
};
template<class T>
class maxPriorityQueue {
private:
node<T>* head;
int size;
int top;
public:
maxPriorityQueue(); //构造函数
~maxPriorityQueue(); //析构函数
int getSize() const; //返回优先级队列的长度
bool isEmpty() const; //判断队列是否为空
T& getTop() const; //返回优先级最高的元素
void pop(); //删除优先级最高的元素
void push(const T& element, int p); //插入元素
};
优先级队列的实现
#include "maxPriorityQueue.h"
template<class T>
maxPriorityQueue<T>::maxPriorityQueue() {
top = 0;
size = 0;
head = new node<T>;
head->next = nullptr;
head->point = 0;
}
template<class T>
maxPriorityQueue<T>::~maxPriorityQueue() {
node<T>* pd = head;
while (pd != nullptr){
node<T>* p = pd->next;
delete pd;
pd = p;
}
}
template<class T>
int maxPriorityQueue<T>::getSize() const {
return size;
}
template<class T>
bool maxPriorityQueue<T>::isEmpty() const {
return size == 0;
}
template<class T>
T &maxPriorityQueue<T>::getTop() const {
node<T>* pd = head;
while (pd->point != top){
pd = pd->next;
}
return pd->data;
}
template<class T>
void maxPriorityQueue<T>::pop() {
node<T>* pd = head;
if(pd->point == top){
head = pd->next;
delete pd;
size--;
return;
}
while (pd->next->point != top){
pd = pd->next;
}
node<T>* dp = pd->next;
pd->next = dp->next;
delete dp;
size--;
pd = head;
int max = 0;
while (pd!= nullptr){
max = max > pd->point? max:pd->point;
pd = pd->next;
}
top = max;
}
template<class T>
void maxPriorityQueue<T>::push(const T &element, int p) {
if (size == 0) {
head->data = element;
head->point = p;
top = p;
} else {
node<T> *pd = head;
while (pd->next != nullptr) {
pd = pd->next;
}
pd->next = new node<T>(element, p);
top = top > p ? top:p;
}
size++;
}
测试程序:
#include <iostream>
using namespace std;
int main(){
maxPriorityQueue<int> maxPriorityQueue;
maxPriorityQueue.push(2,7);
maxPriorityQueue.push(1,4);
maxPriorityQueue.push(7,2);
maxPriorityQueue.push(34,8);
maxPriorityQueue.push(12,6);
maxPriorityQueue.push(23,5);
cout << "size = " << maxPriorityQueue.getSize() << endl;
cout << "top = " << maxPriorityQueue.getTop() << endl;
maxPriorityQueue.pop();
cout << "after pop, top = " << maxPriorityQueue.getTop() << endl;
测试结果:
size = 6
top = 34
after pop, top = 2