import sys
from collections import deque

input = sys.stdin.readline
commands = int(input())
class Queue:
    def __init__(self):
        self.items = deque()

    def push(self, item):
        self.items.append(item)

    def pop(self):
        if self.empty():
            return -1
        return  self.items.popleft()

    def size(self):
        return len(self.items)

    def empty(self):
        return int(len(self.items) == 0)

    def front(self):
        if self.empty():
            return -1
        return self.items[0]

    def back(self):
        if self.empty():
            return -1
        return self.items[-1]



q = Queue()
for _ in range(commands):
    command = input().strip()

    if command.startswith("push"):
        _, num = command.split()
        q.push(num)
    elif command == "pop":
        print(q.pop())
    elif command == "size":
        print(q.size())
    elif command == "empty":
        print(q.empty())
    elif command == "front":
        print(q.front())
    elif command == "back":
        print(q.back())
    else:
        print("not matched")

 

정리

collections.deque 사용

deque는 양쪽에서 O(1) 시간에 삽입/삭제가 가능한 자료구조이므로 큐에 적합

 

 

 

출처 : https://www.acmicpc.net/problem/18258

'Algorithm' 카테고리의 다른 글

BOJ - 24723번 - 녹색거탑  (0) 2025.07.01
BOJ - 15439번 - 베라의 패션  (1) 2025.07.01
BOJ - 28278번 - 스택 2  (0) 2025.06.30
에라토스테네스의 체  (0) 2025.05.28
BOJ - 13909번 - 창문 닫기  (0) 2025.05.28

+ Recent posts