環形隊列的c++實現


隊列是一種先進先出的線性表,隊尾入隊存儲,隊頭出隊讀取。普通隊列在數據出隊列后,使用過的地址空間依然沒有被釋放,產生了很大的浪費。環形隊列可是使數據地址限定在某個范圍內,重復使用。

實現一個環形隊列,基本的功能有

 1 #ifndef MyQueue_h
 2 #define MyQueue_h
 3 
 4 class MyQueue
 5 {
 6 public:
 7     MyQueue(int queueCapacity);     //創建隊列
 8     ~MyQueue();                     //銷毀隊列
 9     void ClearQueue();              //清空隊列
10     bool QueueFull() const;         //隊列判滿
11     bool QueueEmpty() const;        //隊列判空
12     int QueueLength();              //隊列長度
13     bool EnQueue(int element);      //新元素入隊
14     bool DeQueue(int &element);     //首元素出隊
15     void QueueTraverse();           //遍歷隊列
16 private:
17     int *_pQueue;                   //隊列指針
18     int _iQueueLen;                 //隊列長度
19     int _iQueueCapacity;            //隊列容量
20     int _iHead;                     //隊列頭
21     int _iTail;                     //隊列尾
22 }
23 
24 #endif /* MyQueue_h */

構造函數和析構函數實現創建、銷毀隊列並確定隊列容量

 1 MyQueue::MyQueue(int queueCapacity)
 2 {
 3     _iQueueCapacity=queueCapacity;
 4     _pQueue=new int[_iQueueCapacity];
 5     ClearQueue();
 6 }
 7 
 8 MyQueue::~MyQueue()
 9 {
10     delete[] _pQueue;
11     _pQueue=NULL;
12 }

創建隊列時應該隊頭,隊尾和隊列長度都置為零,所以直接使用了作用相同的清空隊列函數

1 void MyQueue::ClearQueue()
2 {
3     _iHead=0;
4     _iTail=0;
5     _iQueueLen=0;
6 }

隊列判空和判滿用於判斷是否能讀取和插入數據

 1 bool MyQueue::QueueFull() const
 2 {
 3     if(_iQueueLen==_iQueueCapacity)
 4     {
 5         return true;
 6     }
 7     else
 8     {
 9         return false;
10     }
11 }
12 
13 bool MyQueue::QueueEmpty() const
14 {
15     if(_iQueueLen==0)
16     {
17         return true;
18     }
19     else{
20         return false;
21     }
22 }

在定義隊列類時,隊列長度寫為了私有類型,所以如果有需要,則須用公有類型的QueueLength()函數得到

1 int MyQueue::QueueLength()
2 {
3     return _iQueueLen;
4 }

環形隊列中,存和取類似,需要注意的是環形問題,比如當隊頭的位置大於隊列容量時,需要通過對隊列容量取余得到正確的隊頭地址,隊尾類似。同時伴隨隊列長度的加減。

 1 bool MyQueue::EnQueue(int element)
 2 {
 3     if(QueueFull())
 4     {
 5         return false;
 6     }
 7     else
 8     {
 9         _pQueue[_iTail]=element;
10         _iTail=++_iTail%_iQueueCapacity;
11         _iQueueLen++;
12         return true;
13     }
14 }
15 
16 bool MyQueue::DeQueue(int &element)
17 {
18     if(QueueEmpty())
19     {
20         return false;
21     }
22     else
23     {
24         element=_pQueue[_iHead];
25         _iHead=++_iHead%_iQueueCapacity;
26         _iQueueLen--;
27         return true;
28     }
29 }

遍歷隊列時,可以用for循環從頭依次輸出,注意定義循環變量i時,i的起始在隊頭,循環次數為隊列長度,所以終止在隊列長度+隊頭。輸出時的地址也應該如存取時一樣,用循環變量對隊列容量取余得到正確的地址。

 1 void MyQueue::QueueTraverse()
 2 {
 3     using namespace std;
 4     
 5     cout<<endl;
 6     for(int i=_iHead;i<_iQueueLen+_iHead;i++)
 7     {
 8         cout<<_pQueue[i%_iQueueCapacity]<<endl;
 9     }
10     cout<<endl;
11 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM