[TIL 210604] 자료구조 #2

송진수·2021년 6월 8일

스택(Stack)

LIFO 구조를 가진 순차적 자료구조

class Stack:
    def __init__(self):
        self.items = []

    def push(self, val):
        self.items.append(val)
    
    def pop(self):
        try:
            return self.items.pop()
        except IndexError:
            print("Stack is empty")
            
    def top(self):
        try:
            return self.items[-1]
        except IndexError:
            print("Stack is empty")
            
    def __len__(self):
        return len(self.items)

주요 메서드

  • push/pop : 파이썬 list의 append와 동일하게 맨 뒤에 데이터 추가/삭제

  • top : 스택에 가장 최근에 들어간 데이터 반환

  • len : Stack 클래스의 인스턴스가 아닌 items 객체의 크기를 반환하도록하는 특수 메서드

수행시간

스택은 push, pop, top, len 모두 O(1)(상수 시간)인 자료구조

스택을 활용한 계산기 코드

profile
보초

0개의 댓글