DevLog:-)

[알고리즘][파이썬]10828-스택 본문

알고리즘/백준

[알고리즘][파이썬]10828-스택

hyeon200 2023. 5. 14. 00:12
반응형

문제

코드

import sys

N = int(input())
stack =[]
for i in range(N):
    S = sys.stdin.readline().split()
    s=S[0]
    if(s =="push"):
        stack.append(S[1])
    elif s=="pop":
        if(not stack):
            print(-1)
        else:
            print(stack.pop())
    elif s=="size":
        print(len(stack))
    elif s=="empty":
        if(not stack):
            print(1)
        else: print(0)
    elif s=="top":
        if(not stack):
            print(-1)
        else:
            print(stack[-1])##

기본 스택 구현 문제이다.

 

tip)

top 코드를 작성할 때 stack[-1]을 사용하면 편하다.

a = [1, 2, 3, ['a', 'b', 'c']]

print(a[-1]) →['a', 'b', 'c']

print(a[-1][0]) →’a’

 

 

반응형