#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 10
//循环队列 长度为 m -1 时即为满
typedef struct {
int front;
int rear;
int* base;
}SqQueue;
//初始化队列
int InitQueue(SqQueue &q) {
q.base = new int[MAXSIZE];
q.front = q.rear = 0;
return 0;
}
//求队列长度
int QueueLength(SqQueue &q) {
return (q.rear - q.front + MAXSIZE) % MAXSIZE;
}
//入队
int EnQueue(SqQueue& q, int n) {
if ((q.rear + 1) % MAXSIZE == q.front) {
printf("队列已满\n");
return 0;
}
else
{
q.base[q.rear] = n;
q.rear = (q.rear + 1) % MAXSIZE;
}
return 0;
}
//出队
int DeQueue(SqQueue& q, int& e) {
if (q.front ==q.rear)
{
return 0;
}
else {
e = q.base[q.front];
q.front = (q.front + 1) % MAXSIZE;
}
return 0;
}
int main() {
SqQueue q;
InitQueue(q);
//入队
for (int i = 0; i < 8; i++)
{
EnQueue(q, i);
}
//打印初始队列
printf("初始队列;");
int len1 = QueueLength(q);
for (int i = q.front; i < len1; i++)
{
printf("%d\t",q.base[i]);
}
printf("\n");
//出队
printf("出队元素:");
for (int i = 0; i < 8; i++)
{
int e;
DeQueue(q,e);
printf("%d\t",e);
}
printf("\n");
int len2 = QueueLength(q);
if (len2 == 0)
{
printf("队列已空\n");
}
else
{
printf("出队后:");
for (int i = 0; i < len2; i++)
{
printf("%d\t", q.base[(q.front + i) % MAXSIZE]);
}
}
return 0;
}