栈 AcWing 828. 模拟栈
原题链接
算法标签
栈
思路
用数组模拟栈, 基本操作如下
代码
#include<bits/stdc++.h>
#define int long long
#define rep(i, a, b) for(int i=a;i<b;++i)
#define Rep(i, a, b) for(int i=a;i>b;--i)
using namespace std;
const int N = 100005;
int stk[N], tt=0;
inline int rd(){
int s=0,w=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')w=-1;ch=getchar();}
while(ch>='0'&&ch<='9') s=s*10+ch-'0',ch=getchar();
return s*w;
}
void put(int x) {
if(x<0) putchar('-'),x=-x;
if(x>=10) put(x/10);
putchar(x%10^48);
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int m=rd();
while(m--){
char s[10];
scanf("%s", s);
if(s[0]=='p'&&s[1]=='u'){
int x=rd();
// 注意 必须为++tt
stk[++tt]=x;
}else if(s[0]=='p'&&s[1]=='o'){
tt--;
}else if(s[0]=='e'){
if(tt>0){
puts("NO");
}else{
puts("YES");
}
}else{
printf("%lld\n", stk[tt]);
}
}
return 0;
}
原创不易
转载请标明出处
如果对你有所帮助 别忘啦点赞支持哈