AcWing - 模拟队列(队列&模拟)
发布日期:2021-07-01 00:21:58 浏览次数:3 分类:技术文章

本文共 1233 字,大约阅读时间需要 4 分钟。

题目链接:

时/空限制:1s / 64MB

题目描述

实现一个队列,队列初始为空,支持四种操作:

(1) “push x” – 向队尾插入一个数x;

(2) “pop” – 从队头弹出一个数;

(3) “empty” – 判断队列是否为空;

(4) “query” – 查询队头元素。

现在要对队列进行M个操作,其中的每个操作3和操作4都要输出相应的结果。

输入格式

第一行包含整数M,表示操作次数。

接下来M行,每行包含一个操作命令,操作命令为”push x”,”pop”,”empty”,”query”中的一种。

输出格式

对于每个”empty”和”query”操作都要输出一个查询结果,每个结果占一行。

其中,”empty”操作的查询结果为“YES”或“NO”,”query”操作的查询结果为一个整数,表示队头元素的值。

数据范围

1≤M≤100000,

1≤x≤10^9,
所有操作保证合法。

输入样例

10

push 6
empty
query
pop
empty
push 3
push 4
pop
query
push 6

输出样例

NO

6
YES
4

解题思路

题意:模拟一个队列,共有四种操作。

思路:直接模拟,写的是数组型的,不过操作和指针的类似。

Accepted Code:

/*  * @Author: lzyws739307453  * @Language: C++  */#include 
using namespace std;const int MAXN = 100005;int Queue[MAXN], front = 0, rear = -1;void push(int x) { Queue[++rear] = x;}void pop() { front++;}bool empty() { return rear < front;}int Query() { return Queue[front];}int main() { char op[7]; int n, k, x; scanf("%d", &n); while (n--) { scanf("%s", op); if (!strcmp(op, "push")) { scanf("%d", &x); push(x); } else if (!strcmp(op, "pop")) pop(); else if (!strcmp(op, "empty")) printf(empty() ? "YES\n" : "NO\n"); else printf("%d\n", Query()); } return 0;}

转载地址:https://lzyws739307453.blog.csdn.net/article/details/99960620 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:AcWing - 单调栈(栈)
下一篇:AcWing - 模拟栈(栈&模拟)

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年04月07日 12时14分12秒