- 직접 구현
import sys
n = int(sys.stdin.readline())
# 이건 느림. n = int(input())
stack = []
for i in range(n):
command = sys.stdin.readline().split()
# 이건 느림. command = input().split()
if command[0] == 'push':
x = int(command[1])
stack.append(x)
if command[0] == 'pop':
if not stack:
print(-1)
else:
print(stack[-1])
stack.pop()
if command[0] == 'size':
print(len(stack))
if command[0] == 'empty':
if not stack:
print(1)
else:
print(0)
if command[0] == 'top':
if not stack:
print(-1)
else:
print(stack[-1])
- 함수 만들어 사용해보기
import sys
def push(x):
stack.append(x)
def pop():
if not stack:
return -1
return stack.pop()
def size():
return len(stack)
def empty():
if not stack:
return 1
return 0
def top():
if not stack:
return -1
return stack[-1]
n = int(sys.stdin.readline())
stack = []
for i in range(n):
command = sys.stdin.readline().split()
if command[0] == 'push':
x = int(command[1])
push(x)
if command[0] == 'pop':
print(pop())
if command[0] == 'size':
print(size())
if command[0] == 'empty':
print(empty())
if command[0] == 'top':
print(top())