본문 바로가기

Python 문법 정복하기

[Python] Stack (LIFO)

'스택'이란 자료 구조는 "빨래통"을 떠올리면 된다.

가장 위에서만 빨래를 빼거나 넣을 수 있는 빨래통!

 

Swift 언어에서의 스택은 어떠한지 코드 예시를 보면서 비교해 보자.


 

Stack 

- 한쪽 끝으로만 자료를 넣고 뺄 수 있는 자료 구조

 

 

빨래통의 특징: Last In First Out = LIFO

 

가장 처음에 넣은 빨래는? 가장 늦게 나온다.

가장 마지막에 넣은 빨래는? 가장 빨리 나온다.

 

 

 

  • push, pop, is_empty
def test_stack():
    stack = Stack()

    stack.push(1)
    stack.push(2)
    stack.push(3)
    stack.push(4)
    stack.push(5)

    assert stack.pop() == 5
    assert stack.pop() == 4
    assert stack.pop() == 3
    assert stack.pop() == 2
    assert stack.pop() == 1
    assert stack.pop() is None
    assert stack.is_empty()

 

class Node:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Stack:
    def __init__(self):
        self.top = None

    def push(self, value):
        self.top = Node(value, self.top)

    def pop(self):
        if self.top is None:
            return None

        node = self.top
        self.top = self.top.next

        return node.val

    def is_empty(self):
        return self.top is None

'Python 문법 정복하기' 카테고리의 다른 글

[Python] Array & LinkedList  (1) 2024.03.23
[Python] Stack 예제  (0) 2024.03.16
[Python] 알고리즘 기초: 공간 복잡도  (0) 2024.03.10
[Python] 알고리즘 기초: 시간 복잡도  (0) 2024.03.10
[Python] Basic (2)  (0) 2024.03.09