c++ 实现优先队列

优先队列底层是堆,下面给出大根堆代码

Push是在新节点到根节点的路径上寻找合适的插入位置;

Pop是删除根节点之后维护大根堆,顺便为最后一个元素寻找合适的位置;

  1 #include<bits/stdc++.h>
  2 
  3 using namespace std;
  4 
  5 template<class T>
  6 class p_queue {
  7 private:
  8     int cap = 10000010;//开辟的空间大小
  9     int size;//当前数据数量
 10     T* data;
 11 
 12 public:
 13     p_queue();
 14     ~p_queue();
 15 
 16     int Size();
 17     bool Empty();
 18     bool Full();
 19     void Push(T key);//堆插入
 20     void Pop();//删除堆顶
 21     T Top();
 22 };
 23 
 24 template<class T>
 25 p_queue<T>::p_queue() {
 26     data = (T*)malloc((cap+1)*sizeof(T));
 27     if (!data) {
 28         perror("传入数据不合法");
 29         return;
 30     }
 31     size = 0;
 32 }
 33 
 34 template<class T>
 35 p_queue<T>::~p_queue() {
 36     while (!Empty())Pop();
 37 }
 38 
 39 template<class T>
 40 int p_queue<T>::Size() {
 41     return size;
 42 }
 43 
 44 template<class T>
 45 bool p_queue<T>::Empty() {
 46     return size == 0;
 47 }
 48 
 49 template<class T>
 50 bool p_queue<T>::Full() {
 51     return size == cap;
 52 }
 53 
 54 template<class T>
 55 void p_queue<T>::Push(T key) {
 56     if (Empty())return data[++size] = key,void();
 57     int i;
 58     for (i = ++size; i > 1 && data[i / 2] < key; i /= 2) {
 59         data[i] = data[i / 2];
 60     }
 61     data[i] = key;
 62 }
 63 
 64 template<class T>
 65 void p_queue<T>::Pop() {
 66     if (Empty()) {
 67         perror("错误:数组为空");
 68         return;
 69     }
 70     int i;
 71     T now = data[size];
 72     --size;
 73     for (i = 1; i*2 <= size;) {
 74         int che = i * 2;
 75         if (che != size && data[che + 1] > data[che])che++;
 76         if (now < data[che]) { data[i] = data[che], i = che; }
 77         else break;
 78     }
 79     data[i] = now;
 80 }
 81 
 82 template<class T>
 83 T p_queue<T>::Top() {
 84     if (Empty()) {
 85         perror("错误:数组为空")。;
 86         return data[0];
 87     }
 88     else return data[1];
 89 }
 90 
 91 int s[10] = { 2,3,5,1,25,1,3,2,4,10 };
 92 
 93 int main() {
 94     p_queue<int> op;
 95     op.Pop();
 96     for (int i = 0; i < 10; i++)op.Push(s[i]);
 97     //for (int i = 1; i <= 10; i++)cout << op.data[i] << " ";
 98     while (!op.Empty()) {
 99         cout << op.Top() << " ";
100         op.Pop();
101     }
102     return 0;
103 }

 

posted @ 2024-06-13 11:24  123123123123123321  阅读(45)  评论(0)    收藏  举报