1.
实现一个栈,栈初始为空,支持四种操作:
push x
– 向栈顶插入一个数 x;pop
– 从栈顶弹出一个数;empty
– 判断栈是否为空;query
– 查询栈顶元素。
#include<iostream>
using namespace std;
const int N=100010;
int a[N];
int main()
{
int M;int tt=-1;
cin>>M;
while(M--)
{
string s;
cin>>s;
if(s=="push")
{
int x;cin>>x;
a[++tt]=x;
}
else if(s=="pop")
{
tt--;
}
else if(s=="empty")
{
if(tt==-1)cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
else
{
cout<<a[tt]<<endl;
}
}
return 0 ;
}
2.
实现一个队列,队列初始为空,支持四种操作:
push x
– 向栈顶插入一个数 x;pop
– 从栈顶弹出一个数;empty
– 判断栈是否为空;query
– 查询栈顶元素。
#include<iostream>
using namespace std;
const int N=1000010;
int a[N];
int main()
{
int M;
cin>>M;
int hh=0,tt=-1;
while(M--)
{
string s;
cin>>s;
if(s=="push")
{
int x;cin>>x;
a[++tt]=x;
}
else if(s=="pop")
{
hh++;
}
else if(s=="empty")
{
if(tt-hh>=0)cout<<"NO"<<endl;
else cout<<"YES"<<endl;
}
else
{
cout<<a[hh]<<endl;
}
}
return 0 ;
}