鸡蛋队列(数组,函数)

时间限制: 1 Sec 内存限制: 128 MB

题目描述

将两根筷子平行的放在一起,就构成了一个队列。将带有编号的鸡蛋放到两根筷子之间叫做入队(push),将筷子之间的鸡蛋拿出来叫做出队(pop)。但这两种方式有特殊的定义,对于入队,只能将鸡蛋从队列的尾部向里放入;对于出队,只能将鸡蛋从队列的头部向外将鸡蛋拿出来。

输入

第一行输入一个数T,表示有T组数据 第二行输入一个数N,表示有N(N<=10)种操作 接下来N行,每行一种操作,push表示将编号为x的鸡蛋放入队列中,pop表示拿走队列头部的一个鸡蛋。 数据输入保证合法,队列中没有鸡蛋时不会有出队操作!

输出

输出N种操作完之后,队列中蛋蛋的编号,如果没蛋了,就输出”no eggs!”(不包括引号)每组输出占一行。

样例输入

2
3
push 1 
push 2
push 3
2
push 1
pop

样例输出

1 2 3
no eggs!

提示

数组模拟队列,用下标记录对头、队尾位置。

解决方案

#include <stdio.h>

struct Queue {
    int data[32];
    int head, tail;
};

void push(struct Queue *queue, int data);
void pop(struct Queue *queue);
void show(struct Queue *queue);

int main() {
    int ctrl;
    scanf("%d", &ctrl);

    while (ctrl--) {
        struct Queue queue = {};
        int time;
        scanf("%d", &time);
        while (time--) {
            char operation[8];
            scanf("%s", operation);
            if (operation[1] == 'u') {
                int data;
                scanf("%d", &data);
                push(&queue, data);
            } else {
                pop(&queue);
            }
        }
        show(&queue);
    }

    return 0;
}

void push(struct Queue *queue, int data) {
    queue->data[queue->tail] = data;
    queue->tail += 1;
}

void pop(struct Queue *queue) {
    queue->head += 1;
}

void show(struct Queue *queue) {
    if (queue->head == queue->tail) {
        printf("no eggs!\n");
    } else {
        printf("%d", queue->data[queue->head]);
        for (int i = queue->head + 1; i != queue->tail; ++i) {
            printf(" %d", queue->data[i]);
        }
        printf("\n");
    }
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注