c语言银行排队问题之单队列
时间: 2023-05-26 09:05:38 浏览: 63
单队列的解决方案如下:
1. 定义一个队列结构,包含以下信息:
- 队列元素数组
- 队列头
- 队列尾
- 队列长度
2. 定义一个结构体,包含每个顾客的信息:
- 姓名
- 操作类型(取钱或存钱)
- 金额
3. 根据输入的顾客信息,创建一个结构体对象,并将其放入队列的尾部。
4. 每次有顾客离开银行,从队列头部取出一个元素,并按照其操作类型分别进行相关操作。
5. 如果队列为空,则表示所有顾客都已经离开银行,结束程序。
代码实现示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_QUEUE_SIZE 100
struct Customer {
char name[20];
char type[4];
int amount;
};
struct Queue {
struct Customer items[MAX_QUEUE_SIZE];
int front, rear;
int size;
};
struct Queue* createQueue() {
struct Queue* q = (struct Queue*)malloc(sizeof(struct Queue));
q->front = -1;
q->rear = -1;
q->size = 0;
return q;
}
int isEmpty(struct Queue* q) {
return q->size == 0;
}
int isFull(struct Queue* q) {
return q->size == MAX_QUEUE_SIZE;
}
void enqueue(struct Queue* q, struct Customer c) {
if (isFull(q)) {
printf("Queue is full.\n");
return;
}
if (isEmpty(q)) {
q->front = 0;
q->rear = 0;
} else {
q->rear = (q->rear + 1) % MAX_QUEUE_SIZE;
}
q->items[q->rear] = c;
q->size++;
}
struct Customer dequeue(struct Queue* q) {
if (isEmpty(q)) {
printf("Queue is empty.\n");
exit(1);
}
struct Customer item = q->items[q->front];
if (q->front == q->rear) {
q->front = -1;
q->rear = -1;
} else {
q->front = (q->front + 1) % MAX_QUEUE_SIZE;
}
q->size--;
return item;
}
void bankSimulator() {
struct Queue* q = createQueue();
int time = 0;
int teller_busy = 0;
struct Customer current_customer;
// simulate customer arrival and departure
while (1) {
// check if customer arrives
if (time % 5 == 0) { // every 5 minutes a customer arrives
struct Customer c;
printf("Enter customer name: ");
scanf("%s", c.name);
printf("Enter operation type (deposit/withdraw): ");
scanf("%s", c.type);
printf("Enter amount: ");
scanf("%d", &c.amount);
enqueue(q, c);
printf("Customer %s joined the queue.\n", c.name);
}
// serve customer if teller is free and there is someone in the queue
if (!isEmpty(q) && teller_busy == 0) {
current_customer = dequeue(q);
teller_busy = 1;
printf("Teller serving customer %s for %s %d.\n",
current_customer.name, current_customer.type, current_customer.amount);
}
// process current customer
if (teller_busy == 1) {
if (strcmp(current_customer.type, "deposit") == 0) {
printf("Depositing %d for customer %s.\n", current_customer.amount, current_customer.name);
} else if (strcmp(current_customer.type, "withdraw") == 0) {
printf("Withdrawing %d for customer %s.\n", current_customer.amount, current_customer.name);
} else {
printf("Invalid operation type.\n");
}
teller_busy = 0;
printf("Customer %s has left the bank.\n", current_customer.name);
}
// check if all customers have left
if (isEmpty(q) && teller_busy == 0) {
break;
}
// increment time by 1 minute
time++;
}
free(q);
}
int main() {
bankSimulator();
return 0;
}
```