#include<stdio.h>
#include<stdlib.h>
typedef struct
{//建立一个结构体
char *elem;
int max_size;//队列最大容量
int f;//队头指针
int r;//队尾指针
}SqQueue;
void main()
{
void init(SqQueue &q,int n);//初始化队列的函数声明
void enQueue(SqQueue &q,char e);//入队的函数声明
void dlQueue(SqQueue &q,char &e);//出队的函数声明
int empty(SqQueue &q);//判断队列是否为空的函数声明
int full(SqQueue &q);//判断队列是否满队的函数说明
int n;//用于接受队列元素个数
char e;//用于接受输入的字符
SqQueue q;
printf("请输入队列的容量n:");
scanf("%d",&n);
init(q,n);//初始化队列q
printf("请输入字符('#'执行一次出队操作,'@'所有元素出队,其他元素入队):");
scanf(" %c",&e);
while(1)
{//根据输入的字符不同分别进行不同的操作
if(e=='#')//输入#,队头元素出队
{
dlQueue(q,e);
printf("出队字符为:%c \n",e);
}
else if(e=='@')//输入@所有元素出队
{
printf("出队字符为:");
do
{
dlQueue(q,e);
printf("%c ",e);
}while(!empty(q));
printf("\n");
}
else //输入其余元素均入队
{
enQueue(q,e);
}
printf("请输入字符('#'执行一次出队操作,'@'所有元素出队,其他元素入队):");
scanf(" %c",&e);
}
}
void init(SqQueue &q,int n)
{//建立一个容量为n的循环队列
q.f=q.r=0;
q.max_size=n+1;//因为是循环队列,则队列最大容量为元素数+1
if(!(q.elem=(char *)malloc(sizeof(char)*(n+1))))exit(-1);
}
int empty(SqQueue &q)
{//判断是否队空
return q.r==q.f;//队空时,队头和队尾指针指向相同
}
int full(SqQueue &q)
{//判断是否队满
return (q.r+1)%q.max_size==q.f;//队满时,队尾指针指向的下一个位置和队头指针一样
}
void enQueue(SqQueue &q,char e)
{
int full(SqQueue &q);//判断队满的函数声明
if(full(q))
{
printf("ERROR!队满\n");
exit(-1);
}
q.r=(q.r+1)%q.max_size;
q.elem[q.r]=e;//先使队尾指针“后退”1,再将元素存进去
}
void dlQueue(SqQueue &q,char &e)
{
int empty(SqQueue &q);//判断队空的函数声明
if(empty(q))
{
printf("ERROR!队空\n");
exit(-1);
}
q.f=(q.f+1)%q.max_size;
e=q.elem[q.f];//先使队头指针“后退”1,再将元素存进去
}
循环队列的基本算法
最新推荐文章于 2023-10-27 18:04:49 发布