本题和上面两题(单链表和双链表)一样,都是用数组来模拟。
#include<iostream>
using namespace std;
const int N=100010;
int stk[N],tt;//stk数组模拟栈,tt是栈顶指针
int main(){
int n;
cin>>n;
while(n--){
string op;
cin>>op;
if(op=="push"){
int x;
cin>>x;
stk[++tt]=x;//push操作
}
else if(op=="pop"){
tt--;//pop操作
}
else if(op=="empty"){//判断是否空
if(tt>0) cout<<"NO"<<endl;
else cout<<"YES"<<endl;
}
else{//查询栈顶元素
cout<<stk[tt]<<endl;
}
}
}