模拟栈
#include <iostream>
#include <string>
using namespace std;
const int N = 100010;
string s;
int n, stk[N], tt;
int main()
{
cin.tie(0);
ios::sync_with_stdio(false);
cin >> n;
while(n -- )
{
int x;
cin >> s;
if(s == "push")
{
cin >> x;
stk[++ tt] = x;
}
else if(s == "pop") tt -- ;
else if(s == "empty") cout << (tt < 0 ? "YES" : "NO") << endl;
else cout << stk[tt] << endl;//取队头元素
}
return 0;
}
模拟队列
#include <iostream>
#include <string>
using namespace std;
const int N = 100010;
string s;
int n, q[N], tt = -1, hh;
int main()
{
cin.tie(0);
ios::sync_with_stdio(false);
cin >> n;
while(n -- )
{
int x;
cin >> s;
if(s == "push")
{
cin >> x;
q[++tt] = x;
}
else if(s == "pop") hh ++ ;
else if(s == "empty") cout << (hh > tt ? "YES" : "NO") << endl;
else cout << q[hh] << endl;//取队头元素
}
return 0;
}
相对于C++STL会快上一点点。