본문 바로가기

백준문제풀이

[백준 문제풀이] 10828번 : 스택

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

 

10828번: 스택

첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지

www.acmicpc.net

 

1. 소스코드

import sys

N=int(sys.stdin.readline())
stack=[]
for i in range(N):
    word=sys.stdin.readline().split()
    order=word[0]

    if order=="push":
        stack.append(word[1])

    elif order=="pop":
        if len(stack)==0:
            print(-1)
        else:
            print(stack.pop())

    elif order=="size":
        print(len(stack))

    elif order =="empty":
        if len(stack)==0:
            print(1)
        else:
            print(0)
            
    elif order=="top":
        if len(stack)==0:
            print(-1)
        else:
            print(stack[-1])