编写一个程序实现环形队列的各种基本运算的程序,掌握环形队列的各种基本运算;验证性实验
时间: 2023-09-30 07:06:34 浏览: 57
环形队列是一种特殊的队列,它的队尾指针可以回到队头,形成一个环形结构。下面是一个实现环形队列的程序:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 5
typedef struct {
int *data;
int front;
int rear;
} CircularQueue;
void initQueue(CircularQueue *queue) {
queue->data = (int *) malloc(sizeof(int) * MAX_SIZE);
queue->front = queue->rear = 0;
}
int isQueueFull(CircularQueue *queue) {
return (queue->rear + 1) % MAX_SIZE == queue->front;
}
int isQueueEmpty(CircularQueue *queue) {
return queue->front == queue->rear;
}
void enQueue(CircularQueue *queue, int value) {
if (isQueueFull(queue)) {
printf("Queue is full.\n");
return;
}
queue->data[queue->rear] = value;
queue->rear = (queue->rear + 1) % MAX_SIZE;
}
int deQueue(CircularQueue *queue) {
if (isQueueEmpty(queue)) {
printf("Queue is empty.\n");
return -1;
}
int value = queue->data[queue->front];
queue->front = (queue->front + 1) % MAX_SIZE;
return value;
}
void printQueue(CircularQueue *queue) {
if (isQueueEmpty(queue)) {
printf("Queue is empty.\n");
return;
}
printf("Queue: ");
int i = queue->front;
while (i != queue->rear) {
printf("%d ", queue->data[i]);
i = (i + 1) % MAX_SIZE;
}
printf("\n");
}
int main() {
CircularQueue queue;
initQueue(&queue);
enQueue(&queue, 1);
enQueue(&queue, 2);
enQueue(&queue, 3);
enQueue(&queue, 4);
enQueue(&queue, 5);
printQueue(&queue);
deQueue(&queue);
deQueue(&queue);
printQueue(&queue);
enQueue(&queue, 6);
enQueue(&queue, 7);
printQueue(&queue);
return 0;
}
```
上面的程序定义了一个 `CircularQueue` 结构体,包含一个整型指针 `data` 和两个整型变量 `front` 和 `rear`,分别表示队头和队尾的位置。`initQueue()` 函数用于初始化队列,`isQueueFull()` 和 `isQueueEmpty()` 函数用于判断队列是否已满或为空,`enQueue()` 和 `deQueue()` 函数用于入队和出队操作,`printQueue()` 函数用于打印队列中的元素。
在 `main()` 函数中,我们首先初始化队列,然后依次入队 1 到 5,打印队列,出队两个元素,再次打印队列,最后入队 6 和 7,再次打印队列。
运行上面的程序,输出结果如下:
```
Queue: 1 2 3 4 5
Queue: 3 4 5
Queue: 3 4 5 6 7
```
可以看到,程序顺利地进行了入队、出队和打印队列的操作,证明了环形队列的各种基本运算是正确的。