본문 바로가기
Problem Solving

[백준] 10828 스택 python 알고리즘 문제

by DuncanKim 2022. 4. 24.
728x90

문제 10828. 스택

1. 나의 코드와 발상 과정

import sys
n = int(input())
queue = []
for _ in range(n):
    order = sys.stdin.readline().strip()
    if order[0:4] == 'push':
        queue.append(int(order[5:]))
    elif order[0:3] == 'top':
        if not queue: 
            print(-1)
        else:
            print(queue[-1])    
    elif order[0:4] == 'size':
        print(len(queue))
    elif order[0:5] == 'empty':
        if len(queue) == 0:
            print(1)
        else:
            print(0)
    else :
        if not queue:
            print(-1)
        else:
            print(queue.pop())

본 문제는 백준의 큐, 덱과 더불어 자료구조 문제의 기본 문제라고 할 수 있다.

 

order라는 변수를 통해 문자를 입력받고, queue라는 리스트에 push를 통해 입력받은 정수들을 저장하고 빼내고 한다.

이때 그 문자가 무엇인지, 그리고 push일 때 저장해야 하는 정수가 무엇인지는 슬라이싱을 통해 구현했다.

 

반복문을 통해서 n번 만큼 반복을 해주었고, print되는 숫자는 리스트를 만들어 따로 저장하여 한번에 출력하지 않고, 바로바로 출력을 걸어서 나올 수 있게 하였다.

 

 

문제출처

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

728x90

댓글