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)(상수 시간)인 자료구조