#include<bits/stdc++.h>
using namespace std;
#define int long long
#define endl '\n'
#define quick ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
const int inf = 0x3f3f3f3f, maxn = 2e5 + 5, mod = 998244353;
inline int read() {
    int s = 0, w = 1;
    char ch = getchar();
    while (ch < '0' || ch > '9') {
        if (ch == '-')w = -1;
        ch = getchar();
    }
    while (ch >= '0' && ch <= '9')s = s * 10 + ch - '0', ch = getchar();
    return s * w;
}
void solve() {
    int q;q=read();
    deque<int>dqe;
    for(int i=1,tmp,cur;i<=q;i++){
        cur=read();
        if(cur==1){
            tmp=read();
            dqe.push_front(tmp);
        }else if(cur==2){
            tmp=read();
            dqe.push_back(tmp);
        }else if(cur==3){
            cout<<dqe.front()<<endl;
            dqe.pop_front();
        }else{
            cout<<dqe.back()<<endl;
            dqe.pop_back();
        }
    }
}
signed main() {
    int t = 1;
//  cin>>t;
    while (t--) {
        solve();
    }
    return 0;
}
/*
STL大法好
*/