隊列的順序儲存結構——迴圈隊列 圖解和代碼實現

來源:互聯網
上載者:User

隊列的順序儲存結構——迴圈隊列

迴圈隊列的長度為(rear-front+QueueSize)%QueueSize

隊空的條件: front=rear

隊滿的條件是: (rear+1)%QueueSize=front

 

 

圖片詳解:

 

 

CirQueue.h

 

//CirQueue.h#ifndef CIRQUEUE_H#define CIRQUEUE_Hconst int QueueSize=100;  //定義儲存隊列元素的數組的最大長度template <class T>        //定義模板類CirQueueclass CirQueue{public:    CirQueue( );        //建構函式,置空隊    ~ CirQueue( );               //解構函式    void EnQueue(T x);           //將元素x入隊    T DeQueue( );                //將隊頭元素出隊    T GetQueue( );               //取隊頭元素(並不刪除)    bool Empty( );               //判斷隊列是否為空白private:    T data[QueueSize];           //存放隊列元素的數組    int front, rear;    //隊頭和隊尾指標,分別指向隊頭元素的前一個位置和隊尾元素的位置};#endif

 

CirQueue.cpp

 

//CirQueue.cpp#include "CirQueue.h"/* * 前置條件:隊列不存在 * 輸    入:無 * 功    能:初始化隊列 * 輸    出:無 * 後置條件:建立一個空隊列 */template <class T>CirQueue<T>::CirQueue( ) {front=rear=0;} /* * 前置條件:隊列已存在 * 輸    入:無 * 功    能:銷毀隊列 * 輸    出:無 * 後置條件:釋放隊列所佔用的儲存空間 */template <class T>CirQueue<T>::~CirQueue( ){}/* * 前置條件:隊列已存在 * 輸    入:元素值x * 功    能:在隊尾插入一個元素 * 輸    出:如果插入不成功,拋出異常 * 後置條件:如果插入成功,隊尾增加了一個元素 */template <class T> void CirQueue<T>::EnQueue(T x){    if ((rear+1) % QueueSize ==front) throw "上溢";    rear=(rear+1) % QueueSize;   //隊尾指標在迴圈意義下加1    data[rear]=x;                //在隊尾處插入元素}/* * 前置條件:隊列已存在 * 輸    入:無 * 功    能:刪除隊頭元素 * 輸    出:如果刪除成功,返回被刪元素值,否則,拋出刪除異常 * 後置條件:如果刪除成功,隊頭減少了一個元素 */template <class T> T CirQueue<T>::DeQueue( ){    if (rear==front) throw "下溢";     front=(front+1) % QueueSize;    //隊頭指標在迴圈意義下加1    return data[front];             //讀取並返回出隊前的隊頭元素,注意隊頭指標}                                   //指向隊頭元素的前一個位置/* * 前置條件:隊列已存在 * 輸    入:無 * 功    能:讀取隊頭元素 * 輸    出:若隊列不空,返回隊頭元素 * 後置條件:隊列不變 */template <class T>T CirQueue<T>::GetQueue( ){       int i;    if (rear==front) throw "下溢";     i=(front+1) % QueueSize;  //注意不要給隊頭指標賦值    return data[i];}/* * 前置條件:隊列已存在 * 輸    入:無 * 功    能:判斷隊列是否為空白 * 輸    出:如果隊列為空白,返回1,否則,返回0 * 後置條件:隊列不變 */template <class T> bool CirQueue<T>::Empty( ) {    if (front==rear) return 1; else return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.