c语言请编写程序实现顺序循环队的建立、入队、出队、输出队列元素的基本操作
时间: 2024-10-18 13:11:57 浏览: 139
在C语言中,我们可以使用数组和指针来实现一个简单的顺序循环队列。这里是一个基础的实现示例:
```c
#include <stdio.h>
#define QUEUE_SIZE 5 // 队列大小
typedef struct {
int data[QUEUE_SIZE]; // 存储数据的数组
int front; // 前端指针
int rear; // 后端指针
} Queue;
// 初始化队列
void initQueue(Queue* queue) {
queue-1;
queue->rear = -1;
}
// 判断队列是否为空
int isQueueEmpty(Queue* queue) {
return queue->front == -1 && queue->rear == -1;
}
// 判断队列是否已满
int isQueueFull(Queue* queue) {
return (queue->front + 1) % QUEUE_SIZE == queue->rear;
}
// 入队操作
void enqueue(Queue* queue, int item) {
if (isQueueFull(queue)) {
printf("Queue is full.\n");
return;
}
queue->rear = (queue->rear + 1) % QUEUE_SIZE; // 循环更新后端
queue->data[queue->rear] = item;
if (queue->front == -1)
queue->front = 0;
}
// 出队操作
int dequeue(Queue* queue) {
if (isQueueEmpty(queue)) {
printf("Queue is empty.\n");
return -1;
}
int item = queue->data[queue->front];
queue->front = (queue->front + 1) % QUEUE_SIZE; // 循环更新前端
return item;
}
// 输出队列元素
void printQueue(Queue* queue) {
if (isQueueEmpty(queue))
printf("Queue is empty.\n");
else {
for(int i = queue->front; i != queue->rear; i = (i+1) % QUEUE_SIZE) {
printf("%d ", queue->data[i]);
}
printf("\n");
}
}
// 主函数演示
int main() {
Queue q;
initQueue(&q);
enqueue(&q, 1);
enqueue(&q, 2);
enqueue(&q, 3);
printQueue(&q); // 输出: 1 2 3
printf("Dequeued element: %d\n", dequeue(&q)); // 输出: 1
printQueue(&q); // 输出: 2 3
return 0;
}
```
这个程序实现了顺序循环队列的基本操作:初始化、判断空满、入队、出队以及打印队列元素。在主函数中,我们先创建了一个队列,然后插入几个元素,接着展示如何出队并打印结果。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)