优先级队列

优先级队列和普通队列并没有特大的不同之处,不一样的地方是,优先级队列的元素具有优先级之分。优先级高的元素在入队的时候应该放在队列前面。我下面实现的优先级队列元素的优先级由其数值大小决定。数值越小,优先级越高。ps:这和按一定规则排序好队列没啥区别啊。

实现如下

//header.h
#ifndef _HEADER_H
#define _HEADER_H #include<iostream> #include<assert.h> #include<string.h> using namespace std; const int DefaultPQSize = 50; template<class T> class PQueue { private: T *pqelements; int count; int maxSize; void adjust(); public: PQueue(int sz = DefaultPQSize); ~PQueue(){delete[]pqelements;} bool Insert(const T& x); bool RemoveMin(T& x);//得到权值最大的元素,即取队头 bool getFront(T& x) const;//得到权值最小的元素,也就是取队尾 void makeEmpty();//置空数组 bool IsEmpty() const{return (this->count==0 ? true : false);} bool IsFull() const{return (this->maxSize==this->count ? true : false);}void print() const; }; template<class T> void PQueue<T>::makeEmpty() { //memset((void)*this->pqelements, '0', sizeof(T)*this->count);很奇怪为啥不让用memset,用了就出错。。 for(int i=0; i<this->count; ++i) this->pqelements[i] = 0; this->count = 0; } template<class T> bool PQueue<T>::getFront(T& x) const { if(!this->IsEmpty()) { x = this->pqelements[this->count-1]; return true; } return false; } template<class T> bool PQueue<T>::RemoveMin(T& x) { if(!this->IsEmpty()) { x = this->pqelements[0]; for(int i=0; i<this->count-1; ++i) this->pqelements[i] = this->pqelements[i+1]; --this->count; return true; } return false; } template<class T> PQueue<T>::PQueue(int sz):maxSize(sz), count(0) { pqelements = new T[maxSize]; assert(pqelements != NULL); } template<class T> bool PQueue<T>::Insert(const T& x) { if(this->IsFull()) { T *newspace = new T[maxSize+DefaultPQSize]; if(newspace == NULL) return false; this->maxSize = maxSize + DefaultPQSize; memcpy((void*)newspace, (void*)this->pqelements, sizeof(T)*this->count); } this->pqelements[this->count++] = x; adjust(); } template<class T> void PQueue<T>::adjust() { if(this->count==0) return; else { for(int i=0; i<this->count-1; ++i) for(int j=i+1; j<this->count; ++j) { if(this->pqelements[i]>this->pqelements[j]) { this->pqelements[i] = this->pqelements[i] + this->pqelements[j]; this->pqelements[j] = this->pqelements[i] - this->pqelements[j]; this->pqelements[i] = this->pqelements[i] - this->pqelements[j]; } } } return; } template<class T> void PQueue<T>::print()const { int i = 0; while(i!=this->count) { cout<<this->pqelements[i++]<<" "; } cout<<endl; } #endif

 

#include"header.h"
int main()
{
    PQueue<int> pq;
    for(int i=0; i<100; ++i)//插入100个元素以检验是否可自动扩容
        pq.Insert(i);    
    pq.print();
    int i = 0;
    if(pq.getFront(i))
        cout<<i<<endl;

    
    if(pq.RemoveMin(i))
        pq.print();
    cout<<i<<endl;

    pq.makeEmpty();
    pq.print();
    return 0;
}

结果如下

 

转载于:https://www.cnblogs.com/area-h-p/p/11305190.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值