IT/알고리즘
[백준] 덱 10866.python
Terriermon
2021. 2. 7. 19:43
문제
- 덱은 push front, push bakc, pop front, pop back이 존재한다.
- 앞선 queue와 stack과 같다.
해설 및 코드
- 시간초과로 인해 sys에서 input을 가져왔다.
- 리스트로 구현
# stack + queue가 섞인 것 = 덱
import sys
# 시간초과 방지
N = int(sys.stdin.readline().rstrip())
arr = []
for _ in range(0, N):
cmd = list(sys.stdin.readline().rstrip().split())
if cmd[0] == 'push_front':
arr.insert(0, cmd[1])
elif cmd[0] == 'push_back':
arr.append(cmd[1])
elif cmd[0] == 'pop_front':
print(arr.pop(0) if len(arr) else -1)
elif cmd[0] == 'pop_back':
print(arr.pop() if len(arr) else -1)
elif cmd[0] == 'size':
print(len(arr))
elif cmd[0] == 'empty':
print(0 if len(arr) else 1)
elif cmd[0] == 'front':
print(arr[0] if len(arr) else -1)
elif cmd[0] == 'back':
print(arr[-1] if len(arr) else -1)
반응형