模拟栈
用数组模拟栈,只需要维护一个指针,因为栈的数据是单方向进入的,所以只需要维护一个指针。
入栈:
stk[++head] = x;
出栈:
head–
查询栈顶元素:
stk[head]
判断是否为空
if(!head)
#include<iostream>
using namespace std;
const int N = 100010;
int head,stk[N];
void push(int x)
{
stk[++head] = x;
}
void pop()
{
head--;
}
int query()
{
return stk[head];
}
int isEmpty()
{
return head;
}
int main()
{
int n;
cin>>n;
while(n --)
{
string op;
int x;
cin >> op;
if( op == "push")
{
cin>>x;
push(x);
}else if( op == "pop" )
{
pop();
}else if(op == "empty")
{
if(!isEmpty())cout<<"Yes"<<endl;
else cout<<"NO"<<endl;
}else
{
cout<<query()<<endl;
}
}
return 0;
}