C语言写一个fifo
时间: 2023-12-12 10:05:11 浏览: 42
在C语言中实现一个FIFO(先进先出)队列可以使用数组或链表两种数据结构,下面给出使用数组实现的示例代码:
```c
#include <stdio.h>
#define MAX_SIZE 10
int fifo[MAX_SIZE];
int front = 0;
int rear = -1;
int count = 0;
void enqueue(int data) {
if (count == MAX_SIZE) {
printf("FIFO is full.\n");
return;
}
rear = (rear + 1) % MAX_SIZE;
fifo[rear] = data;
count++;
}
int dequeue() {
if (count == 0) {
printf("FIFO is empty.\n");
return -1;
}
int data = fifo[front];
front = (front + 1) % MAX_SIZE;
count--;
return data;
}
int main() {
enqueue(1);
enqueue(2);
enqueue(3);
printf("%d\n", dequeue());
printf("%d\n", dequeue());
printf("%d\n", dequeue());
printf("%d\n", dequeue());
enqueue(4);
enqueue(5);
printf("%d\n", dequeue());
printf("%d\n", dequeue());
printf("%d\n", dequeue());
return 0;
}
```
该示例代码使用了循环数组实现,当队列满时,继续插入元素会导致队列溢出,而当队列为空时,继续弹出元素会导致队列下溢。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)