我想要一个c语言的队列函数
时间: 2024-04-30 17:18:26 浏览: 22
以下是一个基于数组实现的简单队列函数的 C 语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100 // 定义队列的最大长度
// 定义队列结构体
typedef struct {
int data[MAX_SIZE]; // 存放队列元素的数组
int front; // 队首指针
int rear; // 队尾指针
} Queue;
// 初始化队列
void initQueue(Queue *q) {
q->front = q->rear = 0;
}
// 入队
int enqueue(Queue *q, int x) {
if ((q->rear + 1) % MAX_SIZE == q->front) { // 队列已满,无法入队
return 0;
} else {
q->data[q->rear] = x;
q->rear = (q->rear + 1) % MAX_SIZE;
return 1;
}
}
// 出队
int dequeue(Queue *q, int *x) {
if (q->front == q->rear) { // 队列为空,无法出队
return 0;
} else {
*x = q->data[q->front];
q->front = (q->front + 1) % MAX_SIZE;
return 1;
}
}
// 获取队首元素
int getFront(Queue *q, int *x) {
if (q->front == q->rear) { // 队列为空,无法获取队首元素
return 0;
} else {
*x = q->data[q->front];
return 1;
}
}
// 判断队列是否为空
int isEmpty(Queue *q) {
return (q->front == q->rear);
}
// 判断队列是否已满
int isFull(Queue *q) {
return ((q->rear + 1) % MAX_SIZE == q->front);
}
int main() {
Queue q;
int x;
initQueue(&q);
enqueue(&q, 1);
enqueue(&q, 2);
enqueue(&q, 3);
while (!isEmpty(&q)) {
dequeue(&q, &x);
printf("%d ", x);
}
printf("\n");
return 0;
}
```
该队列函数实现了队列的基本操作,包括初始化队列、入队、出队、获取队首元素、判断队列是否为空和判断队列是否已满等。你可以根据自己的需求进行修改和扩展。
相关推荐
![](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)