编写C语言程序, 完成模拟银行客户排队叫号过程, 采用链队列设计, 完成如下功能: (1) 初始化银行排队队列; (2) 取号进队; (3) 排队等候; (4) 叫号服务; (5) 不再排队, 怎样处理? (6) 下班后, 怎样销毁队列? (7) 求当前序号前面的排队人数?
时间: 2024-11-05 11:30:21 浏览: 14
银行排队叫号系统实现
5星 · 资源好评率100%
在C语言中编写一个简单的银行客户排队叫号程序,我们可以使用头文件`stdio.h`、`stdlib.h`和自定义结构体以及链表数据结构来完成这个任务。首先,我们创建一个名为`bank_queue.h`的头文件,用于定义结构体和函数原型:
```c
// bank_queue.h
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int customer_id; // 客户编号
struct Node* next; // 链接指针
} QueueNode;
typedef struct BankQueue {
QueueNode* head; // 队首
QueueNode* tail; // 队尾
int customers_in_line; // 当前排队人数
} BankQueue;
void init_bank_queue(BankQueue* queue);
void enqueue(BankQueue* queue, int customer_id);
int dequeue(BankQueue* queue);
void display_queue(BankQueue* queue);
void check_before_service(BankQueue* queue);
void destroy_queue(BankQueue* queue);
```
接下来,我们会在`bank_queue.c`文件中实现这些函数:
```c
// bank_queue.c
#include "bank_queue.h"
void init_bank_queue(BankQueue* queue) {
queue->head = NULL;
queue->tail = NULL;
queue->customers_in_line = 0;
}
void enqueue(BankQueue* queue, int customer_id) {
QueueNode* newNode = (QueueNode*)malloc(sizeof(QueueNode));
if (newNode != NULL) {
newNode->customer_id = customer_id;
newNode->next = NULL;
if (queue->head == NULL) {
queue->head = queue->tail = newNode;
} else {
queue->tail->next = newNode;
queue->tail = newNode;
}
queue->customers_in_line++;
} else {
printf("Memory allocation failed.\n");
}
}
int dequeue(BankQueue* queue) {
if (queue->head == NULL) {
return -1; // 队列为空
}
QueueNode* temp = queue->head;
queue->head = queue->head->next;
if (queue->head == NULL) {
queue->tail = NULL;
}
queue->customers_in_line--;
free(temp); // 释放内存
return temp->customer_id;
}
void display_queue(BankQueue* queue) {
QueueNode* current = queue->head;
while (current != NULL) {
printf("%d ", current->customer_id);
current = current->next;
}
printf("\nCustomers in line: %d\n", queue->customers_in_line);
}
void check_before_service(BankQueue* queue) {
int before_service_num = 0;
QueueNode* prev = NULL;
for (QueueNode* current = queue->head; current != NULL; current = current->next) {
if (prev == NULL || current->customer_id > prev->customer_id) {
before_service_num++;
}
prev = current;
}
printf("Number of customers before service: %d\n", before_service_num);
}
void destroy_queue(BankQueue* queue) {
QueueNode* current = queue->head;
while (current != NULL) {
QueueNode* temp = current;
current = current->next;
free(temp);
}
queue->head = queue->tail = NULL;
}
```
现在你可以使用这些函数来模拟银行排队的过程。例如:
```c
int main() {
BankQueue queue;
init_bank_queue(&queue);
// 插入客户
enqueue(&queue, 1);
enqueue(&queue, 2);
enqueue(&queue, 3);
// 显示排队信息
display_queue(&queue);
// 提供服务
check_before_service(&queue);
// 取消服务
enqueue(&queue, 4); // 新客户进来
// 清理队列
destroy_queue(&queue);
return 0;
}
```
运行此程序将显示客户的编号以及排队信息。每一步骤后,请记得检查相关问题部分:
阅读全文