//循环队列(顺序) A 建一个循环队列。B 连续的入队几个元素,出队几个元素 。C 队满,队空。
#include<cstdio>
#include<cstdlib>
#define MAXQSIZE 10
#define ok 1
#define OVERFLOW -2
#define ERROR 0
typedef struct
{
int * base;
int front;
int rear;
}SqQueue;
int initQueue(SqQueue &Q) // 1
{
Q.base=(int *)malloc(MAXQSIZE *sizeof(int));
if(!Q.base)
exit(OVERFLOW);
Q.front=Q.rear=0;
return ok;
}
int QueueLength(SqQueue Q)
{
return (Q.rear-Q.front+MAXQSIZE)% MAXQSIZE;
}
int EnQueue(SqQueue &Q,int e) // 3
{
if((Q.rear+1)% MAXQSIZE ==Q.front)
{
printf("\n队已满!\n");
return ERROR;
}
Q.base[Q.rear]=e;
Q.rear=(Q.rear+1)% MAXQSIZE;
return ok;
}
int DeQueue(SqQueue &Q,int &e) // 4
{
if(Q.front==Q.rear)
{
printf("\n队已空!\n");
return ERROR;
}
e=Q.base[Q.front];
Q.front=(Q.front+1)% MAXQSIZE;
return ok;
}
int QueueTraverse(SqQueue Q)
{
int i,k;
k=QueueLength(Q);
for(i=1;i<=k;i++)
{
printf("%-3d",Q.base[Q.front]);
Q.front=(Q.front+1)% MAXQSIZE;
}
}
int main()
{
int m,n,e,i;
SqQueue Q;
initQueue(Q);
printf("------------------------------\n");
printf("该循环队列最多可存放%d个元素\n\n",MAXQSIZE-1);
printf("请输入数据元素的个数n\n");
scanf("%d",&n);
printf("请输入%d个整数:\n",n);
for(i=1;i<=n;i++)
{
scanf("%d",&e);
EnQueue(Q,e);
}
printf("q=");
QueueTraverse(Q);
printf("\n");
printf("------------------------------\n");
while(1)
{
printf("1、入队\n");
printf("2、出对\n");
printf("3、退出\n");
printf("请选择你所需要的功能: ");
scanf("%d",&m);
printf("------------------------------\n");
switch(m)
{
case 1:
{
printf("入队的元素是:");
scanf("%d",&e);
EnQueue(Q,e);
printf("q=");
QueueTraverse(Q);
printf("\n");
printf("------------------------------\n");
break;
}
case 2:
{
DeQueue(Q,e);
printf("出队元素是%d\n",e);
printf("q=");
QueueTraverse(Q);
printf("\n");
printf("------------------------------\n");
break;
}
case 3:
return 0;
default:return 0;
}
}
while(1);
return 0;
}
循环队列实验3
最新推荐文章于 2023-07-27 20:22:56 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)