Data structures (with python) - 5. Stack

2024. 1. 7. 21:55ㆍCS - Roadmap.sh/1. Data structures

Data structures (with python) - 5. Stack

 

πŸ’‘ Stack is a linear collection of items where items are inserted and removed in a particular order. Stack is also called a LIFO Data Structure because it follows the “Last In First Out” principle i.e. the item that is inserted in the last is the one that is taken out first.

μŠ€νƒμ€ νŠΉμ • μˆœμ„œλ‘œ ν•­λͺ©μ΄ μ‚½μž…λ˜κ³  μ œκ±°λ˜λŠ” μ„ ν˜• ν•­λͺ© λͺ¨μŒμž…λ‹ˆλ‹€. μŠ€νƒμ€ "μ„ μž…μ„ μΆœ" μ›μΉ™, μ¦‰ κ°€μž₯ λ§ˆμ§€λ§‰μ— μ‚½μž…λœ ν•­λͺ©μ΄ κ°€μž₯ λ¨Όμ € μ œκ±°λ˜λŠ” μ›μΉ™μ„ λ”°λ₯΄κΈ° λ•Œλ¬Έμ— LIFO λ°μ΄ν„° κ΅¬μ‘°λΌκ³ λ„ λΆˆλ¦½λ‹ˆλ‹€.

 

https://ko.wikipedia.org/wiki/%EC%8A%A4%ED%83%9D

 

 

자료ꡬ쑰λ₯Ό κ³΅λΆ€ν•˜λ©΄ 맀번 1μž₯ 1ν•­ 같은 ν•­λͺ©.

μŠ€νƒκ³Ό 큐. 그쀑 μŠ€νƒ(stack) μž…λ‹ˆλ‹€.

 

μŠ€νƒ(Stakc)은 'ν›„μž…μ„ μΆœ', Last in First Out, LIFO 원칙을 λ”°λ₯΄λŠ” μžλ£Œκ΅¬μ‘°μž…λ‹ˆλ‹€.

즉, κ°€μž₯ λ‚˜μ€‘μ— λ“€μ–΄κ°„(ν›„μž…) 데이터가 κ°€μž₯ λ¨Όμ € λ‚˜μ˜€κ²Œ(μ„ μΆœ) λ©λ‹ˆλ‹€.

책을 μŒ“μ•„λ‘κ³  κ°€μž₯ μœ„μ— μžˆλŠ” 책을 λ¨Όμ € κΊΌλ‚΄λŠ” 것 이라고 λΉ„μœ ν• μˆ˜ μžˆμŠ΅λ‹ˆλ‹€.

 

μŠ€νƒμ€ 주둜 두 가지 μ£Όμš” μ—°μ‚°μœΌλ‘œ κ΅¬μ„±λ©λ‹ˆλ‹€.

1. Push : μŠ€νƒμ˜ 맨 μœ„μ— ν•­λͺ©μ„ μΆ”κ°€ν•©λ‹ˆλ‹€.

2. Pop : μŠ€νƒμ˜ 맨 μœ„μ—μ„œ ν•­λͺ©μ„ μ œκ±°ν•˜κ³  κ·Έ ν•­λͺ©μ„ λ°˜ν™˜ν•©λ‹ˆλ‹€.

 

 

In Python

리슀트λ₯Ό μ‚¬μš©ν•΄ μŠ€νƒμ„ κ΅¬ν˜„ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

리슀트 append() λ©”μ„œλ“œλ₯Ό μ‚¬μš©ν•΄μ—¬ push 연산을 κ΅¬ν˜„ν•˜κ³ ,

pop() λ©”μ„œλ“œλ₯Ό μ‚¬μš©ν•΄ pop 연산을 κ΅¬ν˜„ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

 

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

    # μŠ€νƒμ— μš”μ†Œ μΆ”κ°€ (push)
    def push(self, data):
        self.stack.append(data)

    # μŠ€νƒμ˜ 맨 μœ„ μš”μ†Œ 제거 및 λ°˜ν™˜ (pop)
    def pop(self):
        if self.is_empty():
            return None
        else:
            return self.stack.pop()

    # μŠ€νƒμ΄ λΉ„μ–΄μžˆλŠ”μ§€ 확인
    def is_empty(self):
        return len(self.stack) == 0

Stack 클래슀 κ΅¬ν˜„ γ…‡γ…‡

 

s = Stack()

s.push(1)  # 1을 μŠ€νƒμ— μΆ”κ°€
s.push(2)  # 2λ₯Ό μŠ€νƒμ— μΆ”κ°€
s.push(3)  # 3을 μŠ€νƒμ— μΆ”κ°€

print(s.pop())  # 3을 λ°˜ν™˜ν•˜κ³  μŠ€νƒμ—μ„œ 제거
print(s.pop())  # 2λ₯Ό λ°˜ν™˜ν•˜κ³  μŠ€νƒμ—μ„œ 제거
print(s.pop())  # 1을 λ°˜ν™˜ν•˜κ³  μŠ€νƒμ—μ„œ 제거

μœ„ μ½”λ“œμ—μ„œλŠ” 1,2,3 μˆœμ„œλŒ€λ‘œ μŠ€νƒμ— μΆ”κ°€ (push)ν–ˆκ³ ,

이후 μ„Έ 번 pop 연산을 μˆ˜ν–‰ν•˜μ—¬ 3, 2, 1 μˆœμ„œλŒ€λ‘œ 데이터가 λ°˜ν™˜λ˜κ³  μŠ€νƒμ—μ„œ μ œκ±°λ˜λŠ” 것을 확인할 수 μžˆμŠ΅λ‹ˆλ‹€.

μ΄λŠ” μŠ€νƒμ˜ 'ν›„μž…μ„ μΆœ' 원칙을 잘 보여쀀닀.

728x90