본문 바로가기
알고리즘

[python] 백준 28278번 - 스택 2

by 이재현9999 2024. 7. 12.

스택을 구현하는 문제

 

시간 초과 떠서 pypy 3로 풀었다. ㅎ

import sys

N = int(sys.stdin.readline())
stack = []

def one(X):
    stack.append(X)

def two():
    if len(stack) > 0:
        a = stack[-1]
        del(stack[-1])
        print(a)
    else:
        print(-1)

def three():
    print(len(stack))

def four():
    if len(stack) == 0:
        print(1)
    else:
        print(0)

def five():
    if len(stack) > 0:
        print(stack[-1])
    else:
        print(-1)

for i in range(N):
    k = sys.stdin.readline().split()
    command = k[0]
    if command == '1':
        one(int(k[1]))
    elif command == '2':
        two()
    elif command == '3':
        three()
    elif command == '4':
        four()
    elif command == '5':
        five()

 

그렇다면 스택이란 무엇일까?

 

스택(stack)은 후입선출(LIFO, Last In First Out) 원칙에 따라 데이터를 관리하는 자료구조이다.

후입선출이란 마지막에 추가된 요소가 가장 먼저 제거됨을 뜻한다.

 

스택의 주요 연산은 다음과 같다.

 

push: 요소를 스택의 맨 위에 추가한다.

pop: 스택의 맨 위에 있는 요소를 제거하고 반환한다.

peek: 스택의 맨 위에 있는 요소를 반환. 제거는 하지 않는다.

is_empty: 스택이 비어 있는지 확인한다.