1. 程式人生 > >C++優先順序隊列表基本演算法實現

C++優先順序隊列表基本演算法實現

C++優先順序隊列表基本演算法實現

主要採用鏈式結構,進行資料儲存,然後定義一個最後結點指標陣列,將所有優先順序最後一個元素的地址儲存到這個指標陣列中。

#ifndef PriorityQueue_h
#define PriorityQueue_h
#include <iostream>
template <class T>
struct PriorityNode{
    short priority;                 //優先順序
    T data;                         //資料域
    struct PriorityNode<T> * next; //
指標域 }; #define PRIORITY_NUMBER 10 template < class T> class PriorityQueue{ public: PriorityQueue(); ~PriorityQueue(); void Push(T x, short pri); T Pop(); bool Empty(); void PushAdjustLastNodeArray(short pri, PriorityNode<T> *p);//入隊時調整陣列 void PopAdjustLastNodeArray(PriorityNode<T> *p);//
出隊時調整陣列 private: PriorityNode <T> * front; //頭結點 PriorityNode <T> * lastNodeArray[PRIORITY_NUMBER]; //最後結點指標陣列 }; template <class T> PriorityQueue<T>::PriorityQueue(){ front = new PriorityNode <T>; front->next = NULL; for(int i = 0
; i< PRIORITY_NUMBER;i++){ lastNodeArray[i] = front; } } template <class T> PriorityQueue<T>::~PriorityQueue(){ //解構函式 PriorityNode <T> * p = front; while(p){ p = p->next; delete front; front = p; } } template <class T> bool PriorityQueue<T>::Empty(){ if(!front->next) return true; else return false; } template <class T> void PriorityQueue<T>::Push(T x, short pri){ if(pri>=PRIORITY_NUMBER) throw "Priority too great!"; PriorityNode<T> *s = new PriorityNode<T>; s->data = x; s->priority = pri; //新結點加入到鏈中 s->next = lastNodeArray[pri] -> next; lastNodeArray[pri]->next = s; PushAdjustLastNodeArray(pri,s); } template <class T> T PriorityQueue<T>::Pop(){ if(!front->next) throw "Queue is NULL"; PriorityNode<T>*p = front->next; //儲存隊頭結點 front->next = p->next; T x = p->data; PopAdjustLastNodeArray(p); delete p; return x; } template <class T> void PriorityQueue<T>::PushAdjustLastNodeArray(short pri,PriorityNode<T> *p){ short i= pri-1; while (i>=0 && lastNodeArray[i] == lastNodeArray[pri]){ lastNodeArray[i] = p; i--; } lastNodeArray[pri] = p; } template <class T> void PriorityQueue<T>::PopAdjustLastNodeArray(PriorityNode<T> *p){ short pri = p->priority; if(lastNodeArray[pri] == p){ //只有當出隊元素為該優先順序最後一個元素時,才需要調整 PriorityNode<T> * newLastNode = (pri==PRIORITY_NUMBER-1)?front:lastNodeArray[pri+1]; short i = pri - 1; while(i>=0 && lastNodeArray[i] == lastNodeArray[pri]){ lastNodeArray[i] = newLastNode; } lastNodeArray[pri] = newLastNode; } } #endif /* PriorityQueue_h */