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 λ°μ΄ν° ꡬ쑰λΌκ³ λ λΆλ¦½λλ€.
μλ£κ΅¬μ‘°λ₯Ό 곡λΆνλ©΄ λ§€λ² 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 μμλλ‘ λ°μ΄ν°κ° λ°νλκ³ μ€νμμ μ κ±°λλ κ²μ νμΈν μ μμ΅λλ€.
μ΄λ μ€νμ 'νμ μ μΆ' μμΉμ μ 보μ¬μ€λ€.
'CS - Roadmap.sh > 1. Data structures' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
Data structures (with python) - 7. Hash Table (0) | 2024.01.08 |
---|---|
Data structures (with python) - 6. Queue (2) | 2024.01.08 |
Data structures (with python) - 4. Linked List (0) | 2024.01.06 |
Data structures (with python) - 3. Heap (0) | 2024.01.05 |
Data structures (with python) - 2. Graph - 2.4. Graph Representation (1) | 2024.01.04 |