用C语言编写一个程序实现循环队列的初始化,判断队列空否,入队列和出队列等。
时间: 2023-05-29 13:04:38 浏览: 88
数据结构与算法C++实现 循环顺序队列的初始化,求长度,入队,出队
5星 · 资源好评率100%
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 10
typedef struct {
int data[MAX_SIZE];
int front; // 队头指针
int rear; // 队尾指针
} Queue;
// 初始化循环队列
void initQueue(Queue *queue) {
queue->front = 0;
queue->rear = 0;
}
// 判断队列是否为空
int isEmpty(Queue *queue) {
return (queue->front == queue->rear);
}
// 判断队列是否已满
int isFull(Queue *queue) {
return ((queue->rear + 1) % MAX_SIZE == queue->front);
}
// 入队列
int enqueue(Queue *queue, int data) {
if (isFull(queue)) {
printf("Queue is full!\n");
return 0;
}
queue->data[queue->rear] = data;
queue->rear = (queue->rear + 1) % MAX_SIZE;
return 1;
}
// 出队列
int dequeue(Queue *queue, int *data) {
if (isEmpty(queue)) {
printf("Queue is empty!\n");
return 0;
}
*data = queue->data[queue->front];
queue->front = (queue->front + 1) % MAX_SIZE;
return 1;
}
int main() {
Queue queue;
int data;
initQueue(&queue);
enqueue(&queue, 1);
enqueue(&queue, 2);
enqueue(&queue, 3);
dequeue(&queue, &data);
printf("%d ", data);
dequeue(&queue, &data);
printf("%d ", data);
enqueue(&queue, 4);
enqueue(&queue, 5);
enqueue(&queue, 6);
dequeue(&queue, &data);
printf("%d ", data);
dequeue(&queue, &data);
printf("%d ", data);
dequeue(&queue, &data);
printf("%d ", data);
return 0;
}
```
阅读全文