目录
1.循环队列的存储结构
#include <iostream>
using namespace std;
#define QElemType int
#define Status int
#define MAXQSIZE 10
typedef struct
{
QElemType *base;
int front;
int rear;
}SqQueue;
2.循环队列的初始化
Status InitQueue(SqQueue& Q)
{
Q.base = (QElemType*)malloc(MAXQSIZE * sizeof(QElemType));//为队列分配一个最大容量为MAXQSIZE的数组空间
if (!Q.base)
exit(_OVERFLOW); //存储分配失败
Q.front = Q.rear = 0; //头指针和尾指针置为0,队列为空
return 1;
}
3.求队列长度
Status QueueLength(SqQueue Q)
{
return (Q.rear - Q.front + MAXQSIZE) % MAXQSIZE;
}
4.循环队列入队
Status EnQueue(SqQueue& Q, QElemType e)
{
if ((Q.rear + 1) % MAXQSIZE == Q.front) //尾指针在循环意义上加1后等于头指针,表明队满
return 0;
Q.base[Q.rear] = e; //新元素插入队尾
Q.rear = (Q.rear + 1) % MAXQSIZE; //队尾指针加1
return 1;
}
5.循环队列出队
Status DeQueue(SqQueue& Q, QElemType& e)
{
if (Q.front == Q.rear)
return 0;
e = Q.base[Q.front]; //保存队头元素
Q.front = (Q.front + 1) % MAXQSIZE; //队头指针加1
return 1;
}
6.取队头元素
Status GetHead(SqQueue& Q, QElemType& e)
{
if (Q.front == Q.rear)
return 0;
e = Q.base[Q.front]; //返回队头元素的值,队头指针不变
return 1;
}
7.销毁和清除
Status DestroyQueue(SqQueue& Q)
{
while (!QueueEmpty(Q))
{
free(&Q.base[Q.front]);
Q.front = (Q.front + 1) % MAXQSIZE;
}
}
Status ClearQueue(SqQueue& Q)
{
if (QueueEmpty(Q))
return 0;
QElemType i = QueueLength(Q);
while (i--)
{
Q.base[Q.front] = 0;
Q.front = (Q.front + 1) % MAXQSIZE;
}
Q.front = Q.rear = 0;
return 1;
}
8.遍历循环队列
void visit(QElemType a)
{
cout << a<<" ";
}
Status QueueTraverse(SqQueue& Q, void(*visit)(QElemType))
{
if (QueueEmpty(Q))
{
cout << "The queue is empty!\n";
}
else
{
for (int i = Q.front; i != Q.rear; i = (i + 1) % MAXQSIZE)
visit(Q.base[i]);
cout << endl;
}
return 1;
}
9.测试用例
int main()
{
SqQueue Q;
QElemType e;
InitQueue(Q);
cout << "是否为空:" << QueueEmpty(Q) << endl;
for (int i = 0; i < 8; i++)
{
EnQueue(Q, i);
}
cout << "队列元素的个数:" << QueueLength(Q) << endl;
QueueTraverse(Q, visit);
cout << "出队的元素:";
for (int i = 0; i < 4; i++)
{
DeQueue(Q, e);
cout << e << " ";
}
cout << endl;
cout << "是否为空:" << QueueEmpty(Q) << endl;
cout << "队列元素的个数:" << QueueLength(Q) << endl;
for (int i = 0; i < 12; i++)
{
EnQueue(Q, i);
}
cout << "队列元素的个数:" << QueueLength(Q) << endl;
QueueTraverse(Q, visit);
GetHead(Q, e);
cout << "输出队头:" << e << endl;
ClearQueue(Q);
cout << "队列元素的个数:" << QueueLength(Q) << endl;
cout << "是否为空:" << QueueEmpty(Q) << endl;
}
10.判空
Status QueueEmpty(SqQueue Q){
if(Q.front==Q.rear)
return 1;
else
return 0;
}