2023.04.19

10828번: 스택

자료구조 시간에 스택에 대한 내용을 배웠을 것이다. 각각 명령어에 따라서 조건에 맞게 프린트하면 된다.

push -> 스택에 추가 (== stack.append)
top -> 스택 가장 위에 있는 것을 출력 리스트[0]
pop -> 스택 가장 위에 있는 것을 빼온다. (stack.pop)
size -> stack의 사이즈
empty -> stack의 길이가 0 인지 판단.
for i in range(N):
    strings = list(map(str, sys.stdin.readline().split()))

range(N) 을 통해서 한 줄 씩 명령어를 받는다. 해당 strings가 입력 받은 한줄이고, 공백에 따라서 분리된다.

ex) push 3

이라고 입력하면

strings[0] = ‘push’

strings[1] = 3

이 들어간다.

각각 명령어는 strings[0]이 반드시 있고, 그 값에 따라서 기능이 달라지기 떄문에 해당 값을 분기처리하면 된다. case 문을 사용할 지, if 문을 사용할지 취양에 맞게 사용하면 된다.


풀이

import sys

if __name__ == '__main__':
    N = int(sys.stdin.readline())
    stack = []
    for i in range(N):
        strings = list(map(str, sys.stdin.readline().split()))
        if strings[0] == 'push':
            stack.append(int(strings[1]))
        elif strings[0] == 'top':
            if len(stack) == 0:
                print(-1)
            else:
                print(stack[-1])
        elif strings[0] == 'pop':
            if len(stack) == 0:
                print(-1)
            else:
                print(stack.pop())
        elif strings[0] == 'size':
            print(len(stack))
        elif strings[0] == 'empty':
            if len(stack) == 0:
                print(1)
            else:
                print(0)



Tags:

Categories:

Updated:

Leave a comment