给出一个队列使用的例子
时间: 2024-03-23 11:37:26 浏览: 18
假设有一家银行,有多个窗口可以服务客户,客户需要排队等待服务。这时候就可以使用队列来管理客户的排队。
下面给出一个使用队列的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_QUEUE_SIZE 100
// 定义队列结构体
typedef struct {
int data[MAX_QUEUE_SIZE]; // 存储队列元素的数组
int front; // 队头指针
int rear; // 队尾指针
} Queue;
// 初始化队列
void initQueue(Queue *queue) {
queue->front = 0;
queue->rear = 0;
}
// 入队操作
void enqueue(Queue *queue, int element) {
if ((queue->rear + 1) % MAX_QUEUE_SIZE == queue->front) {
printf("队列已满,无法插入元素!\n");
return;
}
queue->data[queue->rear] = element;
queue->rear = (queue->rear + 1) % MAX_QUEUE_SIZE;
}
// 出队操作
int dequeue(Queue *queue) {
if (queue->front == queue->rear) {
printf("队列为空,无法出队!\n");
return -1;
}
int element = queue->data[queue->front];
queue->front = (queue->front + 1) % MAX_QUEUE_SIZE;
return element;
}
// 打印队列中的元素
void printQueue(Queue *queue) {
printf("队列中的元素为:");
int i = queue->front;
while (i != queue->rear) {
printf("%d ", queue->data[i]);
i = (i + 1) % MAX_QUEUE_SIZE;
}
printf("\n");
}
int main() {
Queue queue;
initQueue(&queue);
// 客户进入队列排队
enqueue(&queue, 1);
enqueue(&queue, 2);
enqueue(&queue, 3);
// 打印队列中的元素
printQueue(&queue);
// 客户依次接受服务,离开队列
int element1 = dequeue(&queue);
printf("客户%d接受服务,离开队列\n", element1);
int element2 = dequeue(&queue);
printf("客户%d接受服务,离开队列\n", element2);
int element3 = dequeue(&queue);
printf("客户%d接受服务,离开队列\n", element3);
// 再次打印队列中的元素
printQueue(&queue);
return 0;
}
```
运行上述代码,输出结果如下:
```
队列中的元素为:1 2 3
客户1接受服务,离开队列
客户2接受服务,离开队列
客户3接受服务,离开队列
队列中的元素为:
```
在这个示例中,我们使用队列来实现客户排队的问题。客户进入队列使用`enqueue()`函数,客户依次接受服务、离开队列使用`dequeue()`函数。队列的大小为`MAX_QUEUE_SIZE`,当队列已满时,插入元素会失败。当队列为空时,出队操作会失败。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)