代码主要来源:【数据结构】【清华大学】【严蔚敏】
循环队列基本运算如下:
(1)初始化队列Q
(2)依次进队列元素a,b,c
(3)队列为非空
(4)出队一个元素a
(5)依次进队列元素d,e,f
(6)出队列序列:b c d e f
(7)释放队列
完整代码如下:
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -1
#define TRUE 1
#define FALSE 0
#define MAXQSIZE 10 // 最大队列长度(对于循环队列,最大队列长度要减1),因为要考虑栈满判断条件
typedef char QElemType;
typedef int Status;
typedef struct SqQueue {
QElemType *base; // 初始化的动态分配存储空间
int front; // 头指针,若队列不空,指向队列头元素
int rear; // 尾指针,若队列不空,指向队列尾元素的下一个位置
} SqQueue;
Status InitQueue(SqQueue &Q)
{
// 构造一个空队列Q
Q.base=(QElemType *)malloc(MAXQSIZE*sizeof(QElemType));
if(!Q.base) // 存储分配失败
exit(OVERFLOW);
Q.front=Q.rear=0;
return OK;
}
Status DestroyQueue(SqQueue &Q)
{
// 销毁队列Q,Q不再存在
if(Q.base)
free(Q.base);
Q.base=NULL;
Q.front=Q.rear=0;
return OK;
}
Status QueueEmpty(SqQueue Q)
{
if(Q.front==Q.rear)
return TRUE;
else
return FALSE;
}
int QueueLength(SqQueue Q)
{
// 返回Q的元素个数,即队列的长度
return(Q.rear-Q.front+MAXQSIZE)%MAXQSIZE;
}
Status EnQueue(SqQueue &Q,QElemType e)
{
// 插入元素e为Q的新的队尾元素
if((Q.rear+1)%MAXQSIZE==Q.front) // 队列满
return ERROR;
Q.base[Q.rear]=e;
Q.rear=(Q.rear+1)%MAXQSIZE;
return OK;
}
Status DeQueue(SqQueue &Q,QElemType &e)
{
// 若队列不空,则删除Q的队头元素,用e返回其值,并返回OK;否则返回ERROR
if(Q.front==Q.rear) // 队列空
return ERROR;
e=Q.base[Q.front];
Q.front=(Q.front+1)%MAXQSIZE;
return OK;
}
int main()
{
SqQueue Q;
InitQueue(Q);
char q1[3]={'a','b','c'};
char q2[3]={'d','e','f'};
int i;
char e;
printf("依次进队列元素a,b,c
");
for(i=0;i<3;i++)
{
EnQueue(Q,q1[i]);
}
if(!QueueEmpty(Q))
{
printf("此时栈非空
");
}
DeQueue(Q,e);
printf("出队一个元素:%c
",e);
printf("依次进队列元素d,e,f
");
for(i=0;i<3;i++)
{
EnQueue(Q,q2[i]);
}
printf("出队序列为:");
while(!QueueEmpty(Q))
{
DeQueue(Q,e);
printf("%c ",e);
}
if(DestroyQueue(Q))
{
printf("
释放队列成功!");
}
}