풀이
문제에서 요구하는 것을 스택을 이용해서 잘 구현하면 됩니다.
입력이 많고 시간 제한이 작으므로 빠른 입력을 사용하지 않으면 시간 초과를 받을 수 있으니 주의합시다.
코드
import sys
from collections import deque
input = lambda: sys.stdin.readline().rstrip()
def main():
N = int(input())
stack = deque()
for _ in range(N):
command = input().split()
match command[0]:
case "push":
X = int(command[1])
stack.append(X)
case "pop":
if len(stack) == 0:
print(-1)
else:
print(stack.pop())
case "size":
print(len(stack))
case "empty":
if len(stack) == 0:
print(1)
else:
print(0)
case _: # "top"
if len(stack) == 0:
print(-1)
else:
print(stack[-1])
main()