#include<cstdio>
#include<cmath>
#include<queue>
#include<stack>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int t,n;
int main()
{
int i,j,k;
cin>>t;
char op[10],io[10];
while(t--)
{
scanf("%d%s",&n,op);
if(op[2]=='F')
{
queue<int> q;
while(n--)
{
scanf("%s",io);
if(io[0]=='I')
{
int temp;
scanf("%d",&temp);
q.push(temp);
}
else if(io[0]=='O')
{
if(q.empty())
{
printf("None\n");
}
else
{
int temp=q.front();
q.pop();
printf("%d\n",temp);
}
}
}
}
else if(op[2]=='L')
{
stack<int> q;
while(n--)
{
scanf("%s",io);
if(io[0]=='I')
{
int temp;
scanf("%d",&temp);
q.push(temp);
}
else if(io[0]=='O')
{
if(q.empty())
{
printf("None\n");
}
else
{
int temp=q.top();
q.pop();
printf("%d\n",temp);
}
}
}
}
}
return 0;
}