import sys
from collections import deque
n = int(sys.stdin.readline())
q = deque()
for _ in range(n):
m = sys.stdin.readline().split()
if m[0] == 'push_front':
q.appendleft(m[1])
elif m[0] == 'push_back':
q.append(m[1])
elif m[0] == "pop_front":
if len(q) != 0:
print(q.popleft())
else:
print(-1)
elif m[0] == "pop_back":
if len(q) != 0:
print(q.pop())
else:
print(-1)
elif m[0] == "size":
print(len(q))
elif m[0] == "front":
if len(q) != 0:
print(q[0])
else:
print(-1)
elif m[0] == "back":
if len(q) != 0:
print(q[-1])
else:
print(-1)
elif m[0] == 'empty':
if len(q) != 0:
print(0)
else:
print(1)