import sys
input = sys.stdin.readline
commands = int(input())


class Stack:
    def __init__(self):
        self.items = []

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

    def pop(self):
        if not self.is_empty():
            return self.items.pop()
        return -1

    def peek(self):
        if not self.is_empty():
            return self.items[-1]
        return -1

    def is_empty(self):
        return len(self.items) == 0

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


s = Stack()

for _ in range(commands):
    command = input()
    if command[0] == "1":
        num = int(command[2:])
        s.push(num)
    elif command[0] == "2":
        print(s.pop())
    elif command[0] == "3":
        print(s.size())
    elif command[0] == "4":
        print(int(s.is_empty()))
    elif command[0] == "5":
        print(s.peek())

 

정리

가독성을 위해 class를 사용하여 스택을 구현한다.

전체 시간복잡도는 command(명령어) 만큼 실행하므로 O(N)

 

 

 

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

'Algorithm' 카테고리의 다른 글

BOJ - 15439번 - 베라의 패션  (1) 2025.07.01
BOJ - 28278번 - 큐 2  (0) 2025.06.30
에라토스테네스의 체  (0) 2025.05.28
BOJ - 13909번 - 창문 닫기  (0) 2025.05.28
[프로그래머스] 제출 내역  (0) 2025.04.14

+ Recent posts