算法标签 栈
题目简叙
思路
push
stk[++tt]=tmpN;
pop
tt--;
query
cout<<stk[tt]<<endl;
empty
if(tt>0)cout<<"NO";
else cout<<"YES";
代码
数组模拟
#include<iostream>
#include<string.h>
using namespace std;
const int N = 100000+10;
int stk[N],tt;
int main(){
int m;
cin>>m;
string op;
int tmpN;
while(m--){
cin>>op;
if(op=="push"){
cin>>tmpN;
stk[++tt]=tmpN;
}
else if(op=="query"){
cout<<stk[tt]<<endl;
}
else if(op=="pop"){
tt--;
}
else if(op=="empty"){
if(tt>0)cout<<"NO";
else cout<<"YES";
cout<<endl;
}
}
return 0;
}
STL栈
#include<iostream>
#include<stack>
using namespace std;
stack<int>stk;
int main(){
int n;
cin>>n;
string op;
int tmpN;
while(n--){
cin>>op;
if(op=="query"){
cout<<stk.top()<<endl;
}
else if(op=="push"){
cin>>tmpN;
stk.push(tmpN);
}
else if(op=="pop"){
stk.pop();
}
else if(op=="empty"){
if(stk.empty())cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
}
return 0;
}