#include <iostream>
#include <string>
#include <stack>
#include <queue>
using namespace std;
queue <int> qu;
stack <int> st;
void q(int m)
{
int i, a;
string s1;
while(!qu.empty())
{
qu.pop();
}
for(i = 0; i < m; i++)
{
cin >> s1;
if( s1[0] == 'I')
{
cin >> a;
qu.push(a);
}
if( s1[0] == 'O')
{
if(qu.empty())
{
cout << "None" << endl;
}
else
{
cout << qu.front() << endl;
qu.pop();
}
}
}
}
void s(int m)
{
int i, a;
string s1;
while(!st.empty())
{
st.pop();
}
for(i = 0; i < m; i++)
{
cin >> s1;
if( s1[0] == 'I')
{
cin >> a;
st.push(a);
}
if( s1[0] == 'O')
{
if(st.empty())
{
cout << "None" << endl;
}
else
{
cout << st.top() << endl;
st.pop();
}
}
}
}
int main()
{
int n, m;
string str;
cin >> n;
while ( n-- )
{
cin >> m;
cin >> str;
if(str[2] == 'F')
{
q(m);
}
if(str[2] == 'L')
{
s(m);
}
}
return 0;
}