循环队列的实现
循环队列(C++)
/* ----------------------------自定义循环队列---------------------------------*//* function: * add value into the Queue * delete value from the Queue * count the number of in the Queue * judge the Queue is empty or not * judge the Queue is full or not */#include <iostream>#include <stdlib.h>using namespace std;//the max size is six so the capcity is five#define MAX_SIZE 6typedef int Elemtype;typedef struct { Elemtype data[MAX_SIZE]; int tailIndex; int headIndex;} RoundQueue;//declare the functions in this programvoid initQueue(RoundQueue &);void addValue(RoundQueue & , Elemtype);Elemtype delValue(RoundQueue &);void display(RoundQueue &);bool isEmpty(RoundQueue &);bool isFull(RoundQueue &);int count(RoundQueue &);int main(){ RoundQueue rq; initQueue(rq); for(int i = 0; i < MAX_SIZE - 1; i ++) { addValue(rq , i + 1); } cout << "---------before delete---------" << endl; display(rq); /*Elemtype eDel = delValue(rq); cout << eDel << endl;*/ for(int i = 0; i < MAX_SIZE - 2; i++) { delValue(rq); } cout << "---------after delete---------" << endl; display(rq); for(int i = 0; i < MAX_SIZE - 2; i++) { addValue(rq , i + 1); } cout << "---------add value into the Queue again---------" << endl; display(rq); int iNumber = count(rq); cout << "---------the number of values in the Queue ---------" << endl; cout << iNumber << endl; return 0;}//initial an empty round Queuevoid initQueue(RoundQueue &rq) { rq.headIndex = 0; rq.tailIndex = 0;}//add a value into the round Queuevoid addValue(RoundQueue &rq , Elemtype value) { if(isFull(rq)) { return; } rq.tailIndex = (rq.tailIndex + 1) % MAX_SIZE; rq.data[rq.tailIndex] = value;}//delete a value from the round QueueElemtype delValue(RoundQueue &rq) { //judge the Queue is empty or not if(isEmpty(rq)) { return -1; } //delete the value and move the head index rq.headIndex = (rq.headIndex + 1) % MAX_SIZE; Elemtype eReturn = rq.data[rq.headIndex]; return eReturn;}//display the values in the Queuevoid display(RoundQueue &rq) { //judge the Queue is empty or not if(isEmpty(rq)) { return; } int index = (rq.headIndex + 1) % MAX_SIZE; //display values in the Queue while(true) { cout << rq.data[index] << " "; if(index == rq.tailIndex) { break; } index = (index + 1) % MAX_SIZE; } cout << endl;}//judge the Queue is empty or notbool isEmpty(RoundQueue &rq) { if(rq.headIndex == rq.tailIndex) { return true; } return false;}//judge the Queue is full or notbool isFull(RoundQueue &rq) { if((rq.tailIndex + 1) % MAX_SIZE == rq.headIndex) { return true; } return false;}//count the number of values in the queueint count(RoundQueue &rq) { return (rq.tailIndex - rq.headIndex + MAX_SIZE) % MAX_SIZE;}