#include <stdio.h>
#include <stdlib.h>
#define M 100
int flag=0;
typedef struct SqQueue
{
char *base;
int front;
int rear;
}SqQueue;
void InitQueue(SqQueue *Q)
{
Q->base=(char *)malloc(M*sizeof(char));
if(!Q->base)
exit(-1);
Q->front=Q->rear=0;
}
void CreateQueue(SqQueue *Q)
{
int len,i;
char ch;
printf("请输入队长:\n");
scanf("%d",&len);
while(len<1||len>M)
{
printf("输入队长不符合要求,请输入队长:\n");
scanf("%d",&len);
}
for(i=0;i<len;i++)
{
printf("请输入入队元素:\n");
scanf("%c",&ch);
if((ch=getchar())!='\n')
Q->base[Q->rear++]=ch;
}
flag=1;
}
void EnQueue(SqQueue *Q)
{
if((Q->rear+1)%M==Q->front)
printf("队列已满,无法进行入队操作!\n");
else
{
char ch;
printf("请输入如队列元素:\n");
scanf("%c",&ch);
if((ch=getchar())!='\n')
{
Q->base[Q->rear]=ch;
Q->rear=(Q->rear+1)%M;
}
}
}
void DeQueue(SqQueue *Q)
{
if(Q->front==Q->rear)
printf("循环队列已空,无法进行出队操作!\n");
else
{
char e=Q->base[Q->front];
Q->front=(Q->front+1)%M;
printf("出队元素为:%c\n",e);
}
}
int LengthQueue(SqQueue Q)
{
return (Q.rear+M-Q.front)%M;
}
void EmptyQueue(SqQueue Q)
{
if(Q.front==Q.rear)
printf("队列为空!\n");
else
printf("队列不为空!\n");
}
void DisplayQueue(SqQueue Q)
{
int i;
if(Q.front==Q.rear)
printf("循环队列为空,不能输出!\n");
else
{
for(i=Q.front;i<Q.front+LengthQueue(Q);i++)
printf("%2d\t%2c\n",i+1,Q.base[i%M]);
}
}
void DestroyQueue(SqQueue *Q)
{
if(!Q->base)
printf("循环队列已经被销毁!\n");
else
{
free(Q->base);
Q->front=Q->rear=0;
flag=0;
}
}
void menu()
{
printf("\t循环队列基本实验操作\n");
printf("*********************************\n");
printf("1 建立循环队列!\t\t*\n");
printf("2 循环队列入队操作!\t\t*\n");
printf("3 循环队列出队操作!\t\t*\n");
printf("4 求循环队列长度!\t\t*\n");
printf("5 判断队列是否为空!\t\t*\n");
printf("6 显示队列!\t\t\t*\n");
printf("7 销毁队列!\t\t\t*\n");
printf("0 退出程序!\t\t\t*\n");
printf("*********************************\n");
}
int main()
{
int select;
SqQueue Q;
InitQueue(&Q);
while(1)
{
menu();
printf("请输入要选择的命令:\n");
scanf("%d",&select);
switch(select)
{
case 1:
if(flag==1)
printf("循环链队列已经创建!\n");
else
CreateQueue(&Q);
break;
case 2:
if(flag==0)
printf("循环队列未创建,无法进行如入队操作!\n");
else
EnQueue(&Q);
break;
case 3:
if(flag==0)
printf("循环队列未创建,无法进行如出队操作!\n");
else
DeQueue(&Q);
break;
case 4:
if(flag==0)
printf("循环队列未创建,无法计算队长度!\n");
else
printf("循环队列的长度为:%d\n",LengthQueue(Q));
break;
case 5:
if(flag==0)
printf("循环队列未创建,无法判断队列是否为空!\n");
else
EmptyQueue(Q);
break;
case 6:
if(flag==0)
printf("循环队列未创建,无法显示队列!\n");
else
DisplayQueue(Q);
break;
case 7:
if(flag==0)
printf("循环队列未创建,无法进行销毁队列操作!\n");
else
DestroyQueue(&Q);
break;
case 0:
exit(1);
break;
default :
printf("命令输入有误,请重新输入!\n");
break;
}
}
return 0;
}