#include <iostream>
#include <queue>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n;
cin >> n;
deque<int> dq;
while(n--)
{
int o, t;
cin >> o;
if (o == 1)
{
cin >> t;
dq.push_front(t);
}
else if (o == 2)
{
cin >> t;
dq.push_back(t);
}
else if (o == 3)
{
if (dq.empty())
cout << -1 << "\n";
else
{
cout << dq.front() << "\n";
dq.pop_front();
}
}
else if (o == 4)
{
if (dq.empty())
cout << -1 << "\n";
else
{
cout << dq.back() << "\n";
dq.pop_back();
}
}
else if (o == 5)
cout << dq.size() << "\n";
else if (o == 6)
cout << dq.empty() << "\n";
else if (o == 7)
{
if (dq.empty())
cout << -1 << "\n";
else
cout << dq.front() << "\n";
}
else
{
if (dq.empty())
cout << -1 << "\n";
else
cout << dq.back() << "\n";
}
}
return 0;
}