循环队列(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 6
typedef int Elemtype;
typedef struct {
Elemtype data[MAX_SIZE];
int tailIndex;
int headIndex;
} RoundQueue;
//declare the functions in this program
void 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 Queue
void initQueue(RoundQueue &rq) {
rq.headIndex = 0;
rq.tailIndex = 0;
}
//add a value into the round Queue
void 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 Queue
Elemtype 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 Queue
void 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 not
bool isEmpty(RoundQueue &rq) {
if(rq.headIndex == rq.tailIndex) {
return true;
}
return false;
}
//judge the Queue is full or not
bool isFull(RoundQueue &rq) {
if((rq.tailIndex + 1) % MAX_SIZE == rq.headIndex) {
return true;
}
return false;
}
//count the number of values in the queue
int count(RoundQueue &rq) {
return (rq.tailIndex - rq.headIndex + MAX_SIZE) % MAX_SIZE;
}