4442: 【例15-7】队列-手写队列函数

内存限制:128 MB 时间限制:1.000 S
评测方式:文本比较 命题人:
提交:1 解决:1

题目描述

超市排队(1)。这回小止作为一个收银员在超市打工。收银员会给排在队伍最前面的顾客结账,然后服务队伍中的下一个顾客。而队伍的末尾也一直会有更多的顾客依次加入队列。
最开始时,收银台前面一个人都没有。然后顾客1、顾客2和顾客3排人了队列。收银员给顾客1结账后又给顾客2结账。这时,顾客4和顾客5又加入了队列。在此之后,收银员又给顾客3、顾客4和顾客5结账。此时所有顾客都已经结账,收银台前又没有人了。

把“收银员结账”和“新顾客加入队列”视为事件,那么每次事件之后,队伍会是什么情况呢?排队结账的情况如图15-3所示。

可以发现,如果顾客a比顾客b先排入队伍,那么顾客a比顾客b先结账完成。这种数据结构就是队列。队列是一种“先进先出(First in First Out,FIFO)"的线性表,其限制是允许在表的一端进行删除运算,另外一端进行插入运算。

样例输入 复制


样例输出 复制

Serve customer:[1]
Serve customer:[2]
Serve customer:[3]
Serve customer:[4]
Serve customer:[5]

提示

#include<iostream>
#include<cstdio>
using namespace std;
#define MAXN 1010
int queue[MAXN]; /*开辟队列需要的数组空间,其中MAXN是队列的最大能人元素的次数*/
int head = 0; //队首指针
int tail = 0; //队尾指针,如果有新的元素插人,就会插人到这个位置 
void push(int x) { //进队,需要判断队伍是否溢出
    if (tail >= MAXN)
        printf("Queue overflow.");
    else {
        queue[tail] = x;
        tail += 1;
    }
}
void pop() { //弹出队首元素,需要判断是否队列为空
    if (head == tail)
        printf("Queue is empty");
    else
        head += 1;
}
int front() { //查询队首元素,需要判断是否队列为空
    if (head == tail) {
        printf("Queue is empty");
        return -1;
    } else
        return queue[head];
}

int main() {
    push(1);push(2);push(3);
    printf("Serve customer:[%d]\n", front());pop();
    printf("Serve customer:[%d]\n", front());pop();
    push(4);push(5);
    printf("Serve customer:[%d]\n", front());pop();
    printf("Serve customer:[%d]\n", front());pop();
    printf("Serve customer:[%d]\n", front());pop();
    return 0;
}