利用顺序队列(循环队列)数据结构实现一组数据的存储,并利用简单的交互实现队列的入队和出队。
//ADT 队列(Queue) 顺序存储结构 SqQueue
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 50
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
typedef int ElemType;
typedef int Status;
//定义顺序队列
typedef struct SqQueue
{
ElemType data[MAXSIZE];
int front; //定义顺序队列的头指针
int rear; //定义顺序队列的尾指针
} SqQueue;
//顺序队列的初始化
Status InitQueue(SqQueue *Q)
{
Q->front = 0;
Q->rear = 0;
return 0;
}
//判断顺序队列是否初始化成功
Status QueueEmpty(SqQueue Q)
{
if (Q.front == 0 || Q.rear == 0)
return TRUE;
else
return FALSE;
}
//清空顺序队列
Status ClearQueue(SqQueue *Q)
{
Q->front = 0;
Q->rear = 0;
return OK;
}
//查询顺序队列中的数据元素个数
Status QueueLength(SqQueue Q)
{
int a = 0;
a = (Q.rear - Q.front + MAXSIZE) % MAXSIZE; //为提高数组空间的利用,通过对数组最大值取模构成逻辑上的循环队列
return a;
}
//查询顺序队列队首数据元素的值
Status GetElem(SqQueue Q)
{
if (Q.front == Q.rear)
return ERROR;
printf("顺序队列队首数据元素的值为%d\n", Q.data[Q.front]);
return OK;
}
//顺序队列队尾的插入(入队)
Status QueueInsert(SqQueue *Q, ElemType e)
{
if ((Q->rear + 1) % MAXSIZE == Q->front) //判断顺序队列是否满队
return ERROR;
Q->data[Q->rear] = e;
Q->rear = (Q->rear + 1) % MAXSIZE; //队尾指针后移,利用对MAXSIZE取模来构成逻辑上的循环
return OK;
}
//顺序队列队首的删除(出队)
Status QueueDelete(SqQueue *Q, ElemType *e)
{
if (Q->front == Q->rear)
return ERROR;
*e = Q->data[Q->front]; //将出队数据元素的值传递出来
Q->front = (Q->front + 1) % MAXSIZE;
return OK;
}
//顺序队列数据元素的输入
Status CreateQueue(SqQueue *Q)
{
printf("请输入一组数据元素的值:");
while (TRUE)
{
int a = 0;
scanf("%d", &a);
char c = getchar();
Q->data[Q->rear] = a;
Q->rear = (Q->rear + 1) % MAXSIZE;
if (c == '\n')
break;
}
return OK;
}
//顺序队列的主函数
int main()
{
SqQueue Q;
ElemType e = 0;
Status i = 0;
printf("顺序队列初始化中......\n");
i = InitQueue(&Q);
i = QueueEmpty(Q);
if (i == 0)
printf("顺序队列初始化失败\n");
else
printf("顺序队列初始化成功\n");
i = CreateQueue(&Q);
i = QueueLength(Q);
printf("数据元素存储成功,顺序队列中的数据元素个数为%d\n", i);
while (TRUE)
{
int a = 0;
printf("请选择将要进行的操作:\n1:查询数据元素的个数\n2:查询队首数据元素的值\n3:顺序队列队尾的插入\n4:顺序队列队首的删除\n5:清空顺序队列并结束程序\n");
scanf("%d", &a);
switch (a)
{
case 1:
{
int b = 0;
b = QueueLength(Q);
printf("顺序队列中的数据元素个数为%d\n", b);
break;
}
case 2:
{
int b = 0;
b = GetElem(Q);
if (b == 0)
printf("查询失败\n");
break;
}
case 3:
{
int b = 0;
printf("请输入要入队的值:");
scanf("%d", &e);
b = QueueInsert(&Q, e);
if (b == 0)
printf("入队失败\n");
else
printf("入队成功\n");
break;
}
case 4:
{
int b = 0;
b = QueueDelete(&Q, &e);
if (b == 0)
printf("出队失败\n");
else
printf("出队成功,出队数据元素的值为%d\n", e);
break;
}
case 5:
{
int b = 0;
b = ClearQueue(&Q);
if (b == 0)
printf("顺序队列清空失败\n");
else
printf("顺序队列清空成功\n");
exit(0);
}
default:
break;
}
}
return 0;
}