1. 程式人生 > >數據結構第十一篇——鏈隊列

數據結構第十一篇——鏈隊列

數據 需要 長度 logs cnblogs next color back 判斷

鏈式存儲的隊列稱為鏈隊列。和鏈棧類似,用單鏈表來實現鏈隊,根據隊列的FIFO原則,為了操作上的方便,分別需要一個頭指針和尾指針。隊頭在鏈頭,隊尾在鏈尾。鏈式隊列在進隊時無隊滿問題,但有隊空問題。隊空條件為front->next==NULL。

鏈隊描述如下:

 1 struct Qnode
 2 {
 3     Data data;
 4     QNode *next;
 5 };
 6 
 7 class Queue
 8 {
 9     QNode *front;
10     QNode *rear;
11     
12     public:
13         Queue()
14 { 15 rear=front=new QNode; 16 front->next=NULL; 17 } 18 ~Queur() 19 { 20 ClearQueue(); 21 delete front; 22 } 23 24 void EnQueue(Data item); //入隊 25 Data DeQueue(); //出隊 26
Data GetFront(); //取隊頭元素值 27 void ClearQueue(); //清空隊列 28 bool IsEmpty(); //判斷空否 29 int Length(); //求元素個數 30 }

鏈隊的操作算法描述如下:

 1 //入隊操作
 2 void Queue::EnQueue(Data item)
 3 {
 4     rear->=next=new QNode;
 5     rear=rear->next;
6 rear->data=item; 7 rear->next=NULL: 8 } 9 10 //出隊操作 11 Data Queue::DeQueue() 12 { 13 QNode *p; 14 if(!IsEmpty()) 15 { 16 p=front->next; 17 Data retvalue=p->data; 18 front->next=p->next; 19 delete p; 20 21 if(front->next==NULL) 22 real=front; 23 return retvalue; 24 } 25 else 26 { 27 cout<<"the Queue is empty"<<endl; 28 exit(0); 29 } 30 } 31 32 //取隊頭元素的值 33 Data Queue::GetFront() 34 { 35 if(!IsEmpty()) 36 return front->next->data; 37 else 38 { 39 cout<<"the Queue is empty"<<endl; 40 exit(0); 41 } 42 } 43 44 //清空隊列 45 void Queue::ClearQueue() 46 { 47 rear=front->next; 48 while(rear!=NULL) 49 { 50 front->next=rear->next; 51 delete rear; 52 rear=front->next; 53 } 54 rear=front; 55 } 56 57 //判斷空否 58 bool Queue::IsEmpty() 59 { 60 return (front->next==NULL); 61 } 62 63 //計算隊列長度 64 int Queue::Length() 65 { 66 int cnt=0; 67 QNode *p=pront->next; 68 while(p) 69 { 70 cnt++; 71 p=p->next; 72 } 73 return cnt; 74 }

優先級隊列

  隊列是以FIFO順序訪問元素的數據結構,它從中刪除“最老的”元素。實際應用中常需要另外一種隊列,它刪除優先級最高的元素。這種結構被稱為優先級隊列,主要有插入和刪除操作。

  具體實現不再細說,和普通隊列僅在刪除操作有些許差別。

數據結構第十一篇——鏈隊列