10826(스택) - 자료구조(python)

지환·2023년 10월 3일
0

백준(python)

목록 보기
51/67
post-thumbnail

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

코드

import sys

n = int(sys.stdin.readline())
stack = []
for i in range(n):
    command = sys.stdin.readline().split()

    if command[0] == 'push':
        stack.append(command[1])

    elif command[0] == 'pop':
        if len(stack) > 0:
            print(stack.pop())
        else:
            print(-1)
    
    elif command[0] == 'size':
        print(len(stack))

    elif command[0] == 'empty':
        if len(stack) == 0:
            print(1)
        else:
            print(0)
    
    elif command[0] == 'top':
        if len(stack) > 0:
            print(stack[-1])
        else:
            print(-1)

코드분석

  • command = sys.stdin.readline().split(): 루프 내에서는 표준 입력에서 한 줄을 읽어와 단어로 나누고 결과를 command 리스트에 저장한다.
  • command[0]가 push인 경우, 두 번째 단어(푸시할 값)를 stack에 추가한다.

  • command[0]가 pop인 경우, stack이 비어 있지 않으면 스택의 맨 위 요소를 출력하고 제거한다. 스택이 비어 있다면 -1을 출력한다.

  • command[0]가 size인 경우, 현재 스택의 크기를 출력한다.

  • command[0]가 empty인 경우, 스택이 비어 있는지 확인하고 비어 있다면 1을, 비어 있지 않다면 0을 출력한다.

  • command[0]가 top인 경우, 스택이 비어 있지 않으면 스택의 맨 위 요소를 출력한다. 스택이 비어 있다면 -1을 출력한다.
profile
아는만큼보인다.

0개의 댓글