티스토리 뷰

728x90
반응형

백준 온라인 저지(BOJ) 10828번 스택
https://www.acmicpc.net/problem/10828

 

10828번: 스택

첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지

www.acmicpc.net

* 사용언어 : Python 파이썬
 

1. 문제

정수를 저장하는 스택을 구현 (5가지 명령 수행)
 

2. 풀이

python 배열 내장함수를 활용하여 풀 수 있습니다.
 
LIFO(Last In First Out) 인 stack 자료구조의 특성에 맞게
push, pop, top 명령 모두 배열의 가장 끝 index 에 처리하도록 구현했습니다.
 
파이썬의 경우 index 앞에 minus 를 붙히면 뒤에서 부터 조회할 수 있습니다.
따라서 pop, top 의 경우 st[-1] 로 확인하면 됩니다.
 

3. 코드

# 10828_스택
# 31256KB	48ms
import sys

st = []
#sys.stdin = open('input.txt', 'r')
n = int(sys.stdin.readline())
for i in range(n):
    ip = sys.stdin.readline().split()
    
    match ip[0]:
        case 'push':
            st.append(ip[1])
        case 'pop':
            if len(st) != 0:
                res = st.pop()
                print(res)
            else:
                print(-1)
        case 'size':
            print(len(st))
        case 'empty':
            print(1 if len(st)==0 else 0)
        case 'top':
            print(st[-1] if len(st)!=0 else -1)

* python 삼항 연산자 : [true_value] if [condition] else [false_value]

728x90
반응형
댓글