출처 | https://www.acmicpc.net/problem/10828
import sys
n = int(sys.stdin.readline())
stack = []
for i in range(n):
command = sys.stdin.readline().split()
if command[0] == 'push':
stack.append(command[1])
elif command[0] == 'pop':
if len(stack) > 0:
print(stack.pop())
else:
print(-1)
elif command[0] == 'size':
print(len(stack))
elif command[0] == 'empty':
if len(stack) == 0:
print(1)
else:
print(0)
elif command[0] == 'top':
if len(stack) > 0:
print(stack[-1])
else:
print(-1)
command[0]가 push인 경우, 두 번째 단어(푸시할 값)를 stack에 추가한다.
command[0]가 pop인 경우, stack이 비어 있지 않으면 스택의 맨 위 요소를 출력하고 제거한다. 스택이 비어 있다면 -1을 출력한다.
command[0]가 size인 경우, 현재 스택의 크기를 출력한다.
command[0]가 empty인 경우, 스택이 비어 있는지 확인하고 비어 있다면 1을, 비어 있지 않다면 0을 출력한다.