队空时条件: front=rear
队满时条件: (rear+1)%maxsize=front
front指向队首元素,rear指向队尾元素的下一个元素。
代码如下:
/*
本例用数组来模拟静态循环队列
队列为空的条件:队列中一个元素也没有,即front=rear,但此时front和rear不一定等于0
队列为满的条件:假设创建了一个有6个元素的动态数组,则规定数组中有5个元素即为满
*/
#include <iostream>
using namespace std;
typedef struct Queue
{
int *pBase; //用来创建动态数组,指向动态数组的第一个元素
int front; //队列中队首元素的下标
int rear; //队列中队尾元素的下标加1,rear不是指向最后一个元素,而是最后元素后面的一个
}QUEUE;
void InitQueue(QUEUE *pQ); //初始化一个队列
bool IsEmpty(QUEUE *pQ); //判断队列是否为空
bool IsFull(QUEUE *pQ); //判断队列是否满
void EnQueue(QUEUE *pQ, int value); //入队
void DeQueue(QUEUE *pQ); //出队
void TraverseQueue(QUEUE *pQ);
int main()
{
QUEUE Q;
InitQueue(&Q);
EnQueue(&Q, 1);
EnQueue(&Q, 2);
EnQueue(&Q, 3);
EnQueue(&Q, 4);
EnQueue(&Q, 5);
EnQueue(&Q, 6);
EnQueue(&Q, 7);
EnQueue(&Q, 8);
cout << "队列中元素为: ";
TraverseQueue(&Q);
cout << endl;
DeQueue(&Q);
DeQueue(&Q);
DeQueue(&Q);
cout << "队列中剩余元素为:";
TraverseQueue(&Q);
}
void InitQueue(QUEUE *pQ)
{
pQ->pBase = new int[6];
pQ->front = 0;
pQ->rear = 0;
}
bool IsEmpty(QUEUE *pQ)
{
if(pQ->front == pQ->rear)
return true;
else
return false;
}
bool IsFull(QUEUE *pQ)
{
if((pQ->rear+1)%6 == pQ->front)
return true;
else
return false;
}
void EnQueue(QUEUE *pQ, int value)
{
if(!IsFull(pQ))
{
pQ->pBase[pQ->rear] = value;
pQ->rear = (pQ->rear+1) % 6;
}
else
cout << "队列已满,不能插入数据" << value << endl;
}
void DeQueue(QUEUE *pQ)
{
if(IsEmpty(pQ))
cout << "队列为空,没有数据出队." << endl;
else
{
cout << "出队数据为" << pQ->pBase[pQ->front] << endl;
pQ->front = (pQ->front + 1) % 6;
}
}
void TraverseQueue(QUEUE *pQ)
{
int i = pQ->front;
while(i != pQ->rear)
{
cout << pQ->pBase[i];
i = (i+1) %6;
}
}
运行结果: