1、编写一个程序实现循环队列的各种基本运算,并在此基础上设计一个主程序,完成如下功能: (1)初始化并建立循环队列; (2)入队操作; (3)出队操作; (4)遍历队列; (5)判断队空操作; (6)取队头操作 (7)求队列的长度(队列中元素的个数)
时间: 2024-06-09 16:11:17 浏览: 101
下面是一个基于数组实现的循环队列的示例程序,包含了所有的基本运算及主程序实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 5 //队列容量为5
typedef struct {
int *base; //指向队列空间首地址
int front; //队头指针
int rear; //队尾指针
} SqQueue;
//初始化队列
void InitQueue(SqQueue *Q) {
Q->base = (int *)malloc(MAXSIZE * sizeof(int));
if (!Q->base) {
printf("Memory allocation failed.\n");
exit(-1);
}
Q->front = Q->rear = 0;
}
//入队操作
void EnQueue(SqQueue *Q, int e) {
if ((Q->rear + 1) % MAXSIZE == Q->front) {
printf("Queue is full.\n");
return;
}
Q->base[Q->rear] = e;
Q->rear = (Q->rear + 1) % MAXSIZE;
}
//出队操作
void DeQueue(SqQueue *Q, int *e) {
if (Q->front == Q->rear) {
printf("Queue is empty.\n");
return;
}
*e = Q->base[Q->front];
Q->front = (Q->front + 1) % MAXSIZE;
}
//遍历队列
void TraverseQueue(SqQueue Q) {
int i = Q.front;
while (i != Q.rear) {
printf("%d ", Q.base[i]);
i = (i + 1) % MAXSIZE;
}
printf("\n");
}
//判断队空操作
int QueueEmpty(SqQueue Q) {
if (Q.front == Q.rear)
return 1;
else
return 0;
}
//取队头操作
int GetHead(SqQueue Q, int *e) {
if (Q.front == Q.rear) {
printf("Queue is empty.\n");
return 0;
}
*e = Q.base[Q.front];
return 1;
}
//求队列长度
int QueueLength(SqQueue Q) {
return (Q.rear - Q.front + MAXSIZE) % MAXSIZE;
}
int main() {
SqQueue Q;
int e, len, opt;
InitQueue(&Q); //初始化队列
while (1) {
printf("\n");
printf("1.EnQueue\n");
printf("2.DeQueue\n");
printf("3.TraverseQueue\n");
printf("4.QueueEmpty\n");
printf("5.GetHead\n");
printf("6.QueueLength\n");
printf("7.Exit\n");
printf("Please input your option:");
scanf("%d", &opt);
switch (opt) {
case 1:
printf("Please input the element you want to EnQueue:");
scanf("%d", &e);
EnQueue(&Q, e);
break;
case 2:
DeQueue(&Q, &e);
printf("The element has been DeQueue is:%d\n", e);
break;
case 3:
TraverseQueue(Q);
break;
case 4:
if (QueueEmpty(Q))
printf("The Queue is empty.\n");
else
printf("The Queue is not empty.\n");
break;
case 5:
if (GetHead(Q, &e))
printf("The Queue head element is:%d\n", e);
break;
case 6:
len = QueueLength(Q);
printf("The Queue length is:%d\n", len);
break;
case 7:
exit(0);
default:
printf("Invalid option.\n");
break;
}
}
return 0;
}
```
程序运行截图:
![循环队列程序运行截图](https://img-blog.csdnimg.cn/20210615163348575.png)
阅读全文