题目描述
实现一个栈,栈初始为空,支持四种操作:
(1) “push x” – 向栈顶插入一个数x;
(2) “pop” – 从栈顶弹出一个数;
(3) “empty” – 判断栈是否为空;
(4) “query” – 查询栈顶元素。
输入
10
push 5
query
push 6
pop
query
pop
empty
push 4
query
empty
输出
5
5
YES
4
NO
思路:
- 进栈 stk[++ tt]
- tt > 0 不为空 tt – 出栈
#include<iostream>
using namespace std;
const int N = 1000010;
//数组模拟栈 tt栈顶指针
int stk[N], tt;
int m;
int main(){
cin >> m;
while(m --){
string op;
cin >> op;
int x;
if(op == "push"){
cin >> x;
stk[++ tt] = x;
}else if(op == "pop") tt --;
else if(op == "empty") cout << (tt ? "NO" : "Yes") << endl;
else cout << stk[tt] << endl;
}
return 0;
}