c语言循环队列代码示例
时间: 2024-06-19 13:03:37 浏览: 14
循环队列是一种非常常见的数据结构,下面是一个基于数组实现的C语言循环队列代码示例,你可以参考下:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100 // 定义队列的最大容量为100
typedef struct {
int data[MAXSIZE]; // 存储队列元素
int front; // 队头指针
int rear; // 队尾指针
} Queue;
// 初始化队列
void InitQueue(Queue *q) {
q->front = 0;
q->rear = 0;
}
// 判断队列是否为空
int IsEmpty(Queue *q) {
return q->front == q->rear;
}
// 判断队列是否已满
int IsFull(Queue *q) {
return (q->rear + 1) % MAXSIZE == q->front;
}
// 入队操作
void EnQueue(Queue *q, int x) {
if (IsFull(q)) {
printf("队列已满,无法插入!\n");
return;
}
q->data[q->rear] = x;
q->rear = (q->rear + 1) % MAXSIZE; // 取模是为了让rear回到0
}
// 出队操作
int DeQueue(Queue *q) {
if (IsEmpty(q)) {
printf("队列为空,无法删除!\n");
exit(1);
}
int x = q->data[q->front];
q->front = (q->front + 1) % MAXSIZE; // 取模是为了让front回到0
return x;
}
// 输出队列元素
void PrintQueue(Queue *q) {
printf("队列中的元素为:");
for (int i = q->front; i != q->rear; i = (i + 1) % MAXSIZE) { // 从队头开始遍历
printf("%d ", q->data[i]);
}
printf("\n");
}
int main() {
Queue q;
InitQueue(&q);
EnQueue(&q, 1);
EnQueue(&q, 2);
EnQueue(&q, 3);
PrintQueue(&q);
DeQueue(&q);
PrintQueue(&q);
return 0;
}
```
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)