用C语言写一个队列实现银行取钱模拟
时间: 2023-04-06 22:04:33 浏览: 129
好的,这个问题我可以回答。以下是用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 *q) {
q->front = 0;
q->rear = 0;
}
int isQueueEmpty(Queue *q) {
return q->front == q->rear;
}
int isQueueFull(Queue *q) {
return (q->rear + 1) % MAX_QUEUE_SIZE == q->front;
}
void enqueue(Queue *q, int x) {
if (isQueueFull(q)) {
printf("Queue is full.\n");
exit(1);
}
q->data[q->rear] = x;
q->rear = (q->rear + 1) % MAX_QUEUE_SIZE;
}
int dequeue(Queue *q) {
if (isQueueEmpty(q)) {
printf("Queue is empty.\n");
exit(1);
}
int x = q->data[q->front];
q->front = (q->front + 1) % MAX_QUEUE_SIZE;
return x;
}
int main() {
Queue q;
initQueue(&q);
// 模拟银行取钱
int money[] = {100, 200, 300, 400, 500};
int n = sizeof(money) / sizeof(int);
int i, x;
for (i = 0; i < n; i++) {
enqueue(&q, money[i]);
}
while (!isQueueEmpty(&q)) {
x = dequeue(&q);
printf("取出%d元\n", x);
}
return 0;
}
```
这个代码实现了一个队列,并且用队列模拟了银行取钱的过程。每个人的取钱金额存储在一个数组中,然后依次加入队列中。每次取钱时,从队列中取出一个元素即可。