정수를 저장하는 덱(Deque)를 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.
명령은 총 여덟 가지이다.
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지 않은 명령이 주어지는 경우는 없다.
출력해야하는 명령이 주어질 때마다, 한 줄에 하나씩 출력한다.
15
push_back 1
push_front 2
front
back
size
empty
pop_front
pop_back
pop_front
size
empty
pop_back
push_front 3
empty
front
2
1
2
0
2
1
-1
0
1
-1
0
3
22
front
back
pop_front
pop_back
push_front 1
front
pop_back
push_back 2
back
pop_front
push_front 10
push_front 333
front
back
pop_back
pop_back
push_back 20
push_back 1234
front
back
pop_back
pop_back
-1
-1
-1
-1
1
1
2
2
333
10
10
333
20
1234
1234
20
데크를 사용해서 앞뒤로 넣고 빼고 큐와 스택을 모두 사용할 수 있는지 묻는 문제.
앞에 연습한 스택과 큐로 단련되어있는지 묻는 문제인듯 했다.
from collections import deque
import sys
input = sys.stdin.readline
N = int(input())
q = deque()
for _ in range(N):
order = list(input().split())
if order[0] == 'push_front':
q.appendleft(order[1])
elif order[0] == 'push_back':
q.append(order[1])
elif order[0] == 'pop_front':
if q:
print(q.popleft())
else:
print(-1)
elif order[0] == 'pop_back':
if q:
print(q.pop())
else:
print(-1)
elif order[0] == 'size':
print(len(q))
elif order[0] == 'empty':
if q:
print(0)
else:
print(1)
elif order[0] == 'front':
if q:
print(q[0])
else:
print(-1)
elif order[0] == 'back':
if q:
print(q[-1])
else:
print(-1)