많이 사용되는 자료 구조 중 하나로 LIFO (Last In, First Out) 방식으로 진행된다. 즉, 나중에 들어간 데이터가 먼저 나온다.
class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
print(f"Pushed {item} to stack")
def pop(self):
if not self.is_empty():
return self.stack.pop()
else:
return "Stack is empty"
def is_empty(self):
return len(self.stack) == 0
# 스택 사용 예시
my_stack = Stack()
my_stack.push(1) # 출력: Pushed 1 to stack
my_stack.push(2) # 출력: Pushed 2 to stack
my_stack.push(3) # 출력: Pushed 3 to stack
print(my_stack.pop()) # 출력: 3
print(my_stack.pop()) # 출력: 2
print(my_stack.pop()) # 출력: 1
print(my_stack.pop()) # 출력: Stack is empty
이 예시는 다음과 같이 작동한다:
1. push는 스택에 새로운 데이터를 추가
2. pop는 스택에서 데이터를 제거하고 반환
3. is_empty는 스택이 비어 있는지를 확인