#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<malloc.h>
#define ERROR 0
#define OK 1
#define MAXQSIZE 20
typedef int QElemType; /*队列元素类型,以整型为例实现*/
typedef struct
{
QElemType* base; //指向循环队列的存储空间
int front; //队头指针
int rear; //队尾指针
}SqQueue;
//初始化队列
int InitQueue(SqQueue* Q)
{
Q->base = (QElemType*)malloc(MAXQSIZE * sizeof(QElemType));
if (!Q->base)
return ERROR; //申请存储空间失败
Q->front = Q->rear = 0; //设置队头队尾指针
return OK;
}
//求队长
int QueueLength(SqQueue Q)
{
return(Q.rear - Q.front + MAXQSIZE) % MAXQSIZE;
}
//入队
int EnQueue(SqQueue* Q, QElemType e)
{
if ((Q->rear + 1) % MAXQSIZE == Q->front) //判断对是否已满
return ERROR;
Q->base[Q->rear] = e; //元素e入队
Q->rear = (Q->rear + 1) % MAXQSIZE; //修改队尾指针
return OK;
}
//出队
int DeQueue(SqQueue* Q, QElemType* e)
{
if (Q->front == Q->rear)
return ERROR; //判断队空
*e = Q->base[Q->front]; //*e返回队头元素值
Q->front = (Q->front + 1) % MAXQSIZE; //修改队头指针
return OK;
}
//判队空
int QueueEmpty(SqQueue* Q)
{
if (Q->front == Q->rear)
return OK;
else
return ERROR;
}/*QueueEmpty*/
//取队头
int GetHead(SqQueue* Q, QElemType* e)
{
if (Q->front == Q->rear)
return ERROR;
*e = Q->base[Q->front];
return OK;
}
//销毁队列
int DestroyQueue(SqQueue* Q)
{
if (Q->base)
{
Q->rear = Q->front = 0;
free(Q->base);
}
return OK;
}
//打印队列元素
void Print(SqQueue Q)
{
int len = QueueLength(Q);
for (int i = 0; i < len; i++)
{
printf("%d ", Q.base[Q.front]);
Q.front++;
}
printf("\n");
}
void menu()
{
printf("-------------请选择-------------\n");
printf(" 1.初始化队列 \n");
printf(" 2.求队长 \n");
printf(" 3.入队 \n");
printf(" 4.出队 \n");
printf(" 5.取队头元素 \n");
printf(" 6.销毁队列 \n");
printf(" 0.退出操作 \n");
printf("--------------------------------\n");
}
int main()
{
SqQueue q;
int e1,e2,e3,e4,e5;
//使用队列基本操作完成程序功能
do
{
menu();
scanf("%d", &e1);
switch (e1)
{
case 1:
InitQueue(&q);
printf("初始化成功\n");
break;
case 2:
e2 = QueueLength(q);
printf("队长为:%d\n", e2);
break;
case 3:
printf("请输入入队元素:\n");
scanf("%d", &e3);
EnQueue(&q, e3);
Print(q);
break;
case 4:
DeQueue(&q, &e4);
printf("出队元素为:%d\n", e4);
printf("现队列为: ");
Print(q);
break;
case 5:
GetHead(&q, &e5);
if (q.rear == q.front)
printf("队头元素不存在\n");
else
printf("队头元素为: %d\n", e5);
break;
case 6:
DestroyQueue(&q);
printf("队列已销毁\n");
break;
}
} while (e1);
return 0;
}
06-06
895
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
06-01
184
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
01-20
462
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交