본문 바로가기
백준

[백준] 10828번 파이썬 (스택)

by 헤이즐넛 좋아하는 개발자 2024. 3. 21.

1. 문제와 예제

문제
예제


2. 전체 코드

import sys
input = sys.stdin.readline

# 입력 받기
N = int(input().rstrip()) # 명령의 수
stack = [] # 스택

for _ in range(N):
    com = input().rstrip() # 명령
    # push X
    if (com.split()[0] == 'push'):
        stack.append(com.split()[1])
    # pop
    elif (com == 'pop'):
        l = len(stack)
        if (l == 0):
            print("-1")
        else:
            print(stack.pop(l-1))
    # size
    elif (com == 'size'):
        print(len(stack))
    # empty
    elif (com == 'empty'):
        if (len(stack) == 0):
            print(1)
        else:
            print(0)
    # top
    elif (com == 'top'):
        l = len(stack)
        if (l == 0):
            print("-1")
        else:
            print(stack[l-1])

3. 풀이

stack의 구조를 활용한 가장 기초적인 문제다.

'백준' 카테고리의 다른 글

[백준] 10866번 파이썬 (덱)  (0) 2024.03.21
[백준] 10845번 파이썬 (큐)  (0) 2024.03.21
[백준] 10816번 파이썬 (숫자 카드 2)  (0) 2024.03.21
[백준] 10773번 파이썬 (제로)  (0) 2024.03.20
[백준] 9012번 파이썬 (괄호)  (0) 2024.03.20