模拟队列

题目链接:https://www.acwing.com/problem/content/831/
题意:实现一个队列,队列初始为空,支持四种操作:
(1) “push x” – 向队尾插入一个数x;
(2) “pop” – 从队头弹出一个数;
(3) “empty” – 判断队列是否为空;
(4) “query” – 查询队头元素。
现在要对队列进行M个操作,其中的每个操作3和操作4都要输出相应的结果。
数据范围
1≤M≤1e5,
1≤x≤1e9,
所有操作保证合法。
输入样例:
10
push 6
empty
query
pop
empty
push 3
push 4
pop
query
push 6
输出样例:
NO
6
YES
4
思路:其实STL这些包装好的东西都可以用数组这些简单的东西来实现,它们能实现的数组也可以实现,但是数组能实现的STL却不一定能实现。
代码实现:

#include <iostream>
using namespace std;
const int N = 100010;
int m;
//用hh标记头,tt标记尾
int q[N], hh, tt = -1;
int main()
{
    cin >> m;
    while(m -- ){
        string op;
        int x;
        cin >> op;
        if(op == "push"){
            cin >> x;
            q[ ++ tt] = x;
        }
        else if(op == "pop") hh ++ ;
        else if(op == "empty") cout << (hh <= tt ? "NO" : "YES") << endl;
        else cout << q[hh] << endl;
    }
    return 0;
}

发布了61 篇原创文章 · 获赞 0 · 访问量 963

猜你喜欢

转载自blog.csdn.net/Satur9/article/details/104083049