模板
int stk[N], tt = 0;
stk[ ++ tt] = x;
tt -- ;
stk[tt];
if (tt > 0)
{
}
例题

代码
#include<iostream>
using namespace std;
const int N=100005;
int stk[N];
int tt=0;
void add(int x){
stk[++tt]=x;
}
void del(){
tt--;
}
int value_top(){
return stk[tt];
}
int main(){
int m;
cin>>m;
while(m--){
string op;
int x;
cin>>op;
if(op=="push"){
cin>>x;
add(x);
}else if(op=="pop"){
del();
}else if(op=="query"){
cout<<value_top()<<endl;
}else{
if(tt>0){
cout<<"NO"<<endl;
}else{
cout<<"YES"<<endl;
}
}
}
return 0;
}
当使用tt指向栈顶元素上一个元素时,代码改为:
#include<iostream>
using namespace std;
const int N=100005;
int stk[N];
int tt=0;
void add(int x){
stk[tt++]=x;
}
void del(){
tt--;
}
void value_top(){
tt--;
cout<<stk[tt]<<endl;
tt++;
}
int main(){
int m;
cin>>m;
while(m--){
string op;
int x;
cin>>op;
if(op=="push"){
cin>>x;
add(x);
}else if(op=="pop"){
del();
}else if(op=="query"){
value_top();
}else{
if(tt>=0){
cout<<"NO"<<endl;
}else{
cout<<"YES"<<endl;
}
}
}
return 0;
}