首先先看一下普通的顺序队列
会发现出队后,前面的几个单元不能利用,浪费了空间,如果可以使队列首尾相接就可以解决这个问题了
如何区分队列“空”和“满”
1.另设一个标志位以区分队列是空还是满;
2.少用一个元素空间,当队列头指针在队列尾指针的下一个位置上时为“满”。
当Q.front=Q.rear时队空;Q. rear+1=Q. front时队满
循环队列满足条件 (Q.rear+1)%MAXQSIZE= = Q.front 队满
循环队列的类型定义:
#define MAXQSIZE 100 /*队列的最大长度*/
typedef struct {
QElemType *base; /* 队列的元素空间*/
int front; /*头指针指示器*
int rear; /*尾指针指示器*/
}SqQueue;
(1) 初始化操作
Status InitQueue (SqQueue &Q) {
Q.base = (QElemType * )malloc(MAXQSIZE * sizeof (QElemType));
if ( ! Q. base) exit (OVERFLOW);
Q. front = Q. rear = 0;
return OK;
}
(2) 入队操作
Status EnQueue (SqQueue &Q, QElemType e) {
if ((Q. rear+ 1) % MAXQSIZE == Q. front) return ERROR;
Q.base[Q.rear] = e;
Q.rear = (Q. rear + 1) % MAXQSIZE;
return OK;
}
(3) 出队操作
Status DeQueue (SqQueue &Q, QElemType &e) {
if (Q. front = = Q. rear) return ERROR;
e = Q. base[Q. front];
Q. front = (Q. front + 1) % MAXQSIZE;
return OK;
}
(4) 求队列长度
int QueueLength (SqQueue Q)
{
return (Q. rear - Q. front + MAXQSIZE) % MAXQSIZE;
}
附录:完整代码测试
#include <iostream>
using namespace std;
#define MAXQSIZE 100
#define OK 1
typedef int QElemType;
typedef int Status;
typedef struct Queue
{
QElemType *base;
int font;
int rear;
} LinQueue;
Status InitQueue(LinQueue &Q)
{
Q.base = (QElemType *)malloc(MAXQSIZE * sizeof(QElemType));
if (!Q.base)
exit(0);
Q.font = Q.rear = 0;
return OK;
}
Status EnQueue(LinQueue &Q, QElemType e)
{
if ((Q.rear + 1) % MAXQSIZE == Q.font)
exit(0);
Q.base[Q.rear] = e;
Q.rear = (Q.rear + 1) % MAXQSIZE;
return OK;
}
Status DeQueue(LinQueue &Q, QElemType &e)
{
if (Q.font == Q.rear)
return 0;
e = Q.base[Q.font];
Q.font = (Q.font + 1) % MAXQSIZE;
return OK;
}
Status QueueLength(LinQueue Q)
{
return (Q.rear - Q.font + MAXQSIZE) % MAXQSIZE;
}
void menu()
{
cout << "初始化:1" << endl;
cout << "入队:2" << endl;
cout << "出队:3" << endl;
cout << "求队列的长度:4" << endl;
cout << "退出:5" << endl;
}
int main()
{
LinQueue Q;
while (true)
{
int n;
menu();
scanf("%d", &n);
int e = -1;
switch (n)
{
case 1:
InitQueue(Q);
puts("");
cout << "初始化成功" << endl;
continue;
case 2:
printf("请输入一个元素: ");
scanf("%d", &e);
EnQueue(Q, e);
continue;
case 3:
DeQueue(Q, e);
printf("出队元素是%d\n", e);
continue;
case 4:
e = QueueLength(Q);
printf("队列的长度为%d\n", e);
continue;
default:
break;
}
if (n == 5)
break;
}
}