https://www.acmicpc.net/problem/10866
import sys
from collections import deque
def push_front(x):
queue.appendleft(x)
def push_back(x):
queue.append(x)
def pop_front():
if queue:
return queue.popleft()
else:
return -1
def pop_back():
if queue:
return queue.pop()
else:
return -1
def size():
return len(queue)
def empty():
return 0 if queue else 1
def front():
return queue[0] if queue else -1
def back():
return queue[size() - 1] if queue else -1
queue = deque()
A = int(sys.stdin.readline().rstrip())
for i in range(A):
cmd = sys.stdin.readline().rstrip().split()
command = cmd[0]
if command == 'push_front':
push_front(cmd[1])
elif command == 'push_back':
push_back(cmd[1])
elif command == 'pop_front':
print(pop_front())
elif command == 'pop_back':
print(pop_back())
elif command == 'size':
print(size())
elif command == 'empty':
print(empty())
elif command == 'front':
print(front())
elif command == 'back':
print(back())
pop_front, pop_back, push_front, push_back 때문에 기존에 계속 쓰던 list에서 덱으로 변경을 했다.
덱을 쓰기 위해 from collections import deque 으로 선언을 하고
덱을 사용했다.
pop_front, push_front는 앞에다가 데이터를 넣고 빼는 함수이기 때문에
덱에서 기본 제공 하는 appendleft, popleft 를 사용하여 각각 처리했다.