大学课程免费自学网站微信广告
实现一个栈,栈初始为空,支持四种操作:
-
push x
– 向栈顶插入一个数 x; -
pop
– 从栈顶弹出一个数; -
empty
– 判断栈是否为空; -
query
– 查询栈顶元素。
现在要对栈进行 M 个操作,其中的每个操作 3和操作 4 都要输出相应的结果。
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 100010;
int stk[N],tt;int main()
{tt = 0;//一直表示栈顶元素 每push一个元素 tt+1 此时tt+1就是栈顶int m;cin>>m;while(m--){string op;cin>>op;int x;if(op == "push"){cin>>x;stk[++tt] = x;//入栈 tt+1 tt+1是栈顶}else if(op == "pop"){tt--;//如果一开始tt=5 则stk[5]是栈顶元素 pop一下 stk[4]变成栈顶元素 // tt-1 后面有入栈push的话 stk[5]原有的值正好被取代}else if(op == "empty"){cout<<(tt ? "NO" : "YES")<<endl;// 这里代表 如果tt不是0 那就是no非空 tt是0 就是yes空}else{cout<<stk[tt]<<endl;}}return 0;
}
输入样例:
10 push 5 query push 6 pop query pop empty push 4 query empty
输出样例:
5 5 YES 4 NO
具体模板和算法解释详情见Acwing算法基础课:活动 - AcWing