下面是使用C语言编写的顺序队列模拟业务员到银行排队办理业务的代码示例:

#include <stdio.h>

#define MAX_SIZE 100

typedef struct {
    int queue[MAX_SIZE];
    int front;
    int rear;
} Queue;

void initQueue(Queue *q) {
    q->front = 0;
    q->rear = 0;
}

int isFull(Queue *q) {
    return (q->rear + 1) % MAX_SIZE == q->front;
}

int isEmpty(Queue *q) {
    return q->front == q->rear;
}

void enqueue(Queue *q, int item) {
    if (isFull(q)) {
        printf('队列已满,无法取号排队。\n');
        return;
    }
    q->queue[q->rear] = item;
    q->rear = (q->rear + 1) % MAX_SIZE;
}

int dequeue(Queue *q) {
    if (isEmpty(q)) {
        printf('队列为空,无法办理业务。\n');
        return -1;
    }
    int item = q->queue[q->front];
    q->front = (q->front + 1) % MAX_SIZE;
    return item;
}

void printQueue(Queue *q) {
    if (isEmpty(q)) {
        printf('队列为空。\n');
        return;
    }
    printf('等待办理业务的序号:\n');
    int i;
    for (i = q->front; i != q->rear; i = (i + 1) % MAX_SIZE) {
        printf('%d ', q->queue[i]);
    }
    printf('\n');
}

int getRemainingCustomers(Queue *q) {
    return (q->rear - q->front + MAX_SIZE) % MAX_SIZE;
}

int getCompletedCustomers(Queue *q) {
    return (q->front + MAX_SIZE) % MAX_SIZE;
}

int main() {
    Queue bankQueue;
    initQueue(&bankQueue);
    int choice;
    
    while (1) {
        printf('请选择操作:\n');
        printf('1. 取号排队\n');
        printf('2. 办理业务\n');
        printf('3. 查看等待办理业务的序号\n');
        printf('4. 下班\n');
        
        scanf('%d', &choice);
        
        switch (choice) {
            case 1:
                if (isFull(&bankQueue)) {
                    printf('队列已满,无法取号排队。\n');
                } else {
                    int number = getCompletedCustomers(&bankQueue) + 1;
                    enqueue(&bankQueue, number);
                    printf('取号成功,您的编号是 %d,排在第 %d 位。\n', number, getRemainingCustomers(&bankQueue));
                }
                break;
            case 2:
                if (isEmpty(&bankQueue)) {
                    printf('队列为空,无法办理业务。\n');
                } else {
                    int number = dequeue(&bankQueue);
                    printf('正在为编号为 %d 的客户办理业务。\n', number);
                }
                break;
            case 3:
                printQueue(&bankQueue);
                break;
            case 4:
                printf('下班了!\n');
                printf('剩余未办理业务的编号数量:%d\n', getRemainingCustomers(&bankQueue));
                printf('已经办理完成的编号数量:%d\n', getCompletedCustomers(&bankQueue));
                return 0;
            default:
                printf('无效的选项,请重新输入。\n');
                break;
        }
    }
    
    return 0;
}

这个代码中定义了一个Queue结构体来表示队列,通过初始化队列、判断队列是否满、判断队列是否空、入队、出队、打印队列、获取剩余未办理业务的编号数量以及获取已经办理完成的编号数量等函数来实现相应功能。在主函数中,根据菜单选项进行相应的操作。在每次取号排队时都会打印显示自己的编号和排第几位,下班时会输出队列中剩下的编号和已经办理完成的编号数量。


原文地址: https://www.cveoy.top/t/topic/QXX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录