acwing 828. 模拟栈
题目
实现一个栈,初始为空,支持四种操作:
(1) “push x” – 向栈顶插入一个数x xx;
(2) “pop” – 从栈顶弹出一个数;
(3) “empty” – 判断栈是否为空;
(4) “query” – 查询栈顶元素。
一共进行M MM次操作,操作3 33和4 44需要输出相应的结果。
数据范围
1≤M≤100000 1 ≤ x ≤10^9
输入样例
10 push 5 query push 6 pop query pop empty push 4 query empty
输出样例
5 5 YES 4 NO
来源:模板题,AcWing
#includeusing namespace std; const int N = 100010; int M; int stk[N]; int top = 0; void push(int x) { stk[top++] = x; } void pop() { top--; } bool empty() { return top == 0; } int query() { return stk[top - 1]; } int main() { cin >> M; while (M--) { string op; cin >> op; int x; if (op == "push") { cin >> x; push(x); } else if (op == "pop") pop(); else if (op == "empty") cout << (empty() ? "YES" : "NO") << endl; else if (op == "query") cout << query() << endl; } return 0; }