隊列的順序儲存結構——迴圈隊列
迴圈隊列的長度為(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;}