#include<bits/stdc++.h>
using namespace std;
void read(int &x)
{
char ch = getchar();
x = 0;
for (; ch < ‘0‘ || ch > ‘9‘; ch = getchar());
for (; ch >=‘0‘ && ch <= ‘9‘; ch = getchar()) x = x * 10 + ch - ‘0‘;
}
list<int>li[150005];
int main()
{
int n,q;
while(~scanf("%d%d",&n,&q))
{
for(int i=1; i<=n; i++)li[i].clear();
for(int i=1,op,u,v,w,val; i<=q; i++)
{
read(op);
switch(op)
{
case 1:
{
read(u),read(w),read(val);
if(w==1)li[u].push_back(val);
else li[u].push_front(val);
break;
}
case 2:
{
read(u),read(w);
if(w==1)
{
if(li[u].empty())printf("-1\n");
else
{
printf("%d\n",*li[u].rbegin()),li[u].pop_back();
}
}
else
{
if(li[u].empty())printf("-1\n");
else printf("%d\n",*li[u].begin()),li[u].pop_front();
}
break;
}
case 3:
{
read(u),read(v),read(w);
if(w==1)li[v].reverse(),li[u].splice(li[u].end(),li[v]),li[v].clear();
else li[u].splice(li[u].end(),li[v]),li[v].clear();
}
}
}
}
return 0;
}