boj/백준-18258-python

cosmos·2022년 2월 4일
0
post-thumbnail

문제

풀이

  • 정수를 저장하는 큐를 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.
  • 명령은 총 여섯 가지이다.
    1) push X: 정수 X를 큐에 넣는 연산이다.
    2) pop: 큐에서 가장 앞에 있는 정수를 빼고, 그 수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
    3) size: 큐에 들어있는 정수의 개수를 출력한다.
    4) empty: 큐가 비어있으면 1, 아니면 0을 출력한다.
    5) front: 큐의 가장 앞에 있는 정수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.
    6) back: 큐의 가장 뒤에 있는 정수를 출력한다. 만약 큐에 들어있는 정수가 없는 경우에는 -1을 출력한다.

코드

# boj, 18258: 큐 2, python3
from collections import deque

def push(queue, x):
    queue.appendleft(x)

def pop(queue):
    if not queue:
        print(-1)
    else:
        print(queue[-1])
        queue.pop()

def size(queue):
    print(len(queue))

def empty(queue):
    if not queue:
        print(1)
    else:
        print(0)

def front(queue):
    if queue:
        print(queue[-1])
    else:
        print(-1)

def back(queue):
    if queue:
        print(queue[0])
    else:
        print(-1)

def solve(order_list):
    queue = deque()

    for x in order_list:
        if x == 'pop':
            pop(queue)
        elif x == 'size':
            size(queue)
        elif x == 'empty':
            empty(queue)
        elif x == 'front':
            front(queue)
        elif x == 'back':
            back(queue)
        else:
            push_num = x.split()[-1]
            push(queue, push_num)

if __name__ == '__main__':
    n = int(input())
    order_list = [str(input()) for _ in range(n)]

    solve(order_list)

결과

출처 & 깃허브

boj
github

0개의 댓글