栈 : 先进后出
队列 : 先进先出
1. 栈
#include<iostream>
using namespace std;
const int N=1e5+10;
int stk[N],tt; //这里tt是栈顶
int main ()
{
int m;
cin>>m;
while (m--)
{
string s;
cin>>s;
int x;
if (s=="push")
{
cin>>x;
stk[++tt]=x;
//先++是为了方面输出栈顶
}
else if (s=="pop") tt--;
else if (s=="empty") cout<<(tt ? "NO" : "YES")<<endl;
else cout<<stk[tt]<<endl;
//如果前面是tt++,那么这里就要是tt-1
}
return 0;
}
2. 队列
#include<iostream>
using namespace std;
const int N=1e5+10;
int q[N],hh,tt=-1; //这里tt是队顶,hh是队尾
int main ()
{
int m;
cin>>m;
while (m--)
{
string s;
cin>>s;
int x;
if (s=="push")
{
cin>>x;
q[++tt]=x;
}
else if (s=="pop") hh++;
else if (s=="empty") cout<<(hh<=tt ? "NO" : "YES")<<endl;
else cout<<q[hh]<<endl;
}
return 0;
}