编写一个C程序实现顺序队列的各种基本操作,并在此基础上设计一个主程序,完成如下功能: 1)建立循环队列 2)入队列 3)出队列 4)判断队列是否为空 5)遍历队列 6)取队首元素
时间: 2024-10-23 14:14:44 浏览: 50
在C语言中,我们可以使用数组来实现一个简单的循环队列。这里是一个基础的实现,包含顺序队列的基本操作以及主程序:
```c
#include <stdio.h>
#define QUEUE_SIZE 10
#define FRONT -1
#define REAR (QUEUE_SIZE - 1)
typedef struct {
int data[QUEUE_SIZE];
int front;
int rear;
} Queue;
// 初始化队列
void init(Queue* queue) {
queue->front = FRONT;
queue->rear = REAR;
}
// 判断队列是否为空
int is_empty(Queue* queue) {
return queue->front == queue->rear;
}
// 入队操作
void enqueue(Queue* queue, int item) {
if ((queue->rear + 1) % QUEUE_SIZE != FRONT) { // 防止溢出
queue->rear = (queue->rear + 1) % QUEUE_SIZE;
queue->data[queue->rear] = item;
printf("Enqueue: %d\n", item);
} else {
printf("Queue is full.\n");
}
}
// 出队操作
int dequeue(Queue* queue) {
if (!is_empty(queue)) {
int item = queue->data[queue->front];
queue->front = (queue->front + 1) % QUEUE_SIZE;
printf("Dequeue: %d\n", item);
return item; // 返回队首元素
} else {
printf("Queue is empty.\n");
return -1; // 或者抛出异常
}
}
// 遍历队列
void traverse(Queue* queue) {
if (queue->front != queue->rear) {
for (int i = queue->front; i != queue->rear; i = (i + 1) % QUEUE_SIZE) {
printf("%d ", queue->data[i]);
}
printf("\n");
} else {
printf("Queue is empty or contains only one element.\n");
}
}
int main() {
Queue my_queue;
init(&my_queue);
// 主程序示例
enqueue(&my_queue, 10);
enqueue(&my_queue, 20);
enqueue(&my_queue, 30); // ...更多入队操作
traverse(&my_queue); // 遍历队列
int first_element = dequeue(&my_queue); // 取队首元素并出队
printf("First element after dequeue: %d\n", first_element);
return 0;
}
```
这个程序首先初始化一个循环队列,然后执行一系列的入队、出队、遍历和查看队列是否为空的操作。请注意,在实际应用中,你可以根据需要添加错误处理和其他细节。
阅读全文
相关推荐
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.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://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)