[Python] 스택(Stack) 구현하기

orangesnail·2025년 3월 8일

Python

목록 보기
17/21

자료구조를 구현하며 파이썬 코딩 능력을 키우는 것이 목표라서 각 자료구조에 대한 자세한 설명은 생략하겠다.


스택의 특징

  1. LIFO (Last-In-First-Out) - 급식판이 쌓아져 있는 더미를 생각하면 이해하기 쉽다. 가장 위에 있는 급식판을 가장 먼저 집어야 한다.
  2. 스택에 요소를 추가하는 것은 push, 스택에서 요소를 제거하는 것은 pop이라고 부른다.

리스트를 사용해 스택 구현하기

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

    def push(self, item):
        self.stack.append(item)

    def pop(self):
        if not self.is_empty():
            return self.stack.pop()
        return None

    def peek(self):
        if not self.is_empty():
            return self.stack[-1]
        return None

    def is_empty(self):
        return len(self.stack) == 0
    
    def show(self):
        print(self.stack)

실행해보기

stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
stack.show()

print(stack.pop())
stack.show()

print(stack.peek())

print(stack.is_empty())

profile
초보입니다. 피드백 환영합니다 😗

0개의 댓글