알고리즘/백준
[백준] 10828번 스택 (Python)
wookcode
2021. 3. 13. 23:17
728x90
반응형
문제

10828번: 스택
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
코드
import sys
N = int(input())
stack = []
a = []
def push(X):
stack.append(X)
def pop():
if not stack:
return -1
else:
return stack.pop()
def size():
return len(stack)
# false = 0, true =1
def empty():
if stack:
return 0
else:
return 1
def top():
if not stack:
return -1
else:
return stack[-1]
for i in range(N):
a=sys.stdin.readline().split()
if a[0] == 'push':
push(int(a[1]))
elif a[0] == 'top':
print(top())
elif a[0] == 'size':
print(size())
elif a[0] == 'empty':
print(empty())
elif a[0] == 'pop':
print(pop())
코드설명
스택을 직접 구현하는 문제인데 반복문에서 input()으로 받게되면 시간초과가 떠서 sys를 import해줘서
sys.stdin.readline()으로 받아줬다.
반응형