题目传送门

一、理解与感悟

AcWing 828. 模拟栈 1、$tt$确定初始值是$0$,但增加时++$tt$, 就是实际上数组是从$1$开始的。

2、弹出就\(tt\)--,指针变了,但多余的数据不用清除,不碍事。

3、\(tt\)回到\(0\),就是一个都没有了。

4、用数组模拟栈,比\(STL\)\(stack\)方便、速度快,可以遍历到栈中每一个元素。

二、完整代码

#include <bits/stdc++.h>

using namespace std;
const int N = 100010;
int stk[N], tt;
string cmd;

int main() {
    //优化输入
    ios::sync_with_stdio(false);
    int n;
    cin >> n;
    while (n--) {
        cin >> cmd;
        if (cmd == "push") {
            int x;
            cin >> x;
            stk[++tt] = x;
        } else if (cmd == "pop")
            tt--;
        else if (cmd == "query")
            printf("%d\n", stk[tt]);
        else if (cmd == "empty") {
            if (tt == 0) printf("YES\n");
            else printf("NO\n");
        }
    }
    return 0;
}

相关文章: