Stack ใน Python คืออะไร?
Stack เป็น Linear Data Structure ทำงานแบบ Last In First Out (LIFO) Element ที่เข้าไปสุดท้ายจะถูก Process ก่อน (เหมือนกองจาน)
ตัวอย่างในชีวิตจริง
กองจาน: จานแรกอยู่ล่างสุด จานสุดท้ายอยู่บนสุด ต้องการจาน ต้องยกจานบนสุดออกก่อน (Last In First Out)
การ Implement Stack ใน Python
วิธีที่ 1: ใช้ List (Simple แต่ไม่ค่อยมีประสิทธิภาพ)
Operations:
append(item)- Push: เพิ่ม Element ท้าย Stackpop()- Pop: ลบและคืน Element ท้าย Stack (LIFO)
stack = []
stack.append(1)
stack.append(2)
stack.append(3)
print("Initial Stack:", stack) # [1, 2, 3]
print("Element popped from the stack")
print(stack.pop()) # 3
print(stack.pop()) # 2
print("Stack after popping:", stack) # [1]
# Pop from empty -> IndexError
# stack.pop() # IndexError: pop from empty list
วิธีที่ 2: ใช้ queue.LifoQueue (Thread-Safe, Built-in)
from queue import LifoQueue
s = LifoQueue(maxsize=3) # maxsize=0 = unlimited
s.put(1)
s.put(2)
s.put(3)
print("Is stack full:", s.full()) # True
print("Element popped from the stack")
print(s.get()) # 3
print(s.get()) # 2
print("Number of elements in stack:", s.qsize()) # 1
print("Is stack empty:", s.empty()) # False
Methods ของ LifoQueue
| Method | Description |
|---|---|
| put(item) | Push item, block ถ้า Full |
| put_nowait(item) | Push item, raise Exception ถ้า Full |
| get() | Pop item, block ถ้า Empty |
| get_nowait() | Pop item, raise Exception ถ้า Empty |
| full() | True ถ้า Full |
| empty() | True ถ้า Empty |
| qsize() | จำนวน Elements |
วิธีที่ 3: ใช้ collections.deque (แนะนำ - เร็วที่สุด)
from collections import deque
stack = deque()
stack.append(1)
stack.append(2)
stack.append(3)
print("Initial stack:", stack) # deque([1, 2, 3])
print("Element popped from the stack")
print(stack.pop()) # 3
print(stack.pop()) # 2
print("Stack after popping:", stack) # deque([1])
# Pop from empty -> IndexError
# stack.pop() # IndexError
ทำไม deque ดีกว่า List?
append()และpop()เป็น O(1) ทั้งคู่- List:
pop()ท้ายเป็น O(1) แต่pop(0)เป็น O(n) - deque Thread-Safe สำหรับ Single Producer/Consumer
- Memory Efficient
Stack Class แบบ Custom (Encapsulation)
class Stack:
def __init__(self):
self._items = []
def push(self, item):
self._items.append(item)
def pop(self):
if self.is_empty():
raise IndexError("Pop from empty stack")
return self._items.pop()
def peek(self):
if self.is_empty():
raise IndexError("Peek from empty stack")
return self._items[-1]
def is_empty(self):
return len(self._items) == 0
def size(self):
return len(self._items)
def __str__(self):
return str(self._items)
# ใช้งาน
s = Stack()
s.push(10)
s.push(20)
print(s.peek()) # 20
print(s.pop()) # 20
print(s) # [10]
ประยุกต์ใช้: Balanced Parentheses
def is_balanced(s):
stack = []
pairs = {')': '(', ']': '[', '}': '{'}
for char in s:
if char in '([{':
stack.append(char)
elif char in ')]}':
if not stack or stack.pop() != pairs[char]:
return False
return not stack
print(is_balanced("({[]})")) # True
print(is_balanced("({[})")) # False