본문 바로가기
Beakjoon&프로그래머스/파이썬

[백준/파이썬]10866번 덱

by 현장 2021. 5. 6.

-코드

from sys import stdin
from collections import deque
r = deque()
for i in range(int(input())):
    c = stdin.readline().split()

    if c[0] == 'push_front':
        r.appendleft(c[1])
    elif c[0] == 'push_back':
        r.append(c[1])
    elif c[0] == 'pop_front':
        if len(r) == 0:
            print(-1)
        else:
            print(r.popleft())
    elif c[0] == 'pop_back':
        if len(r) == 0:
            print(-1)
        else:
            print(r.pop())
    elif c[0] == 'size':
        print(len(r))
    elif c[0] == 'empty':
        if len(r) == 0:
            print(1)
        else:
            print(0)
    elif c[0] == 'front':
        if len(r) == 0:
            print(-1)
        else:
            print(r[0])
    elif c[0] == 'back':
        if len(r) == 0:
            print(-1)
        else:
            print(r[-1])

스택이라는 문제를 풀었을 때, 비슷해서 해봤으나 pop_front와 push_front에서 막혀서 찾아보니 deque를 사용해서 pop과 append를 왼쪽부터 넣을 수 있는 것을 알게 되어서 해결할 수 있었습니다.