|5. Stack आणि Queue
Chapter 5DSA (Data Structures & Algorithms)~1 min read

Stack आणि Queue

LIFO आणि FIFO Structures

Stack म्हणजे LIFO (Last In, First Out) — जे शेवटी गेलं ते आधी बाहेर येतं. Queue म्हणजे FIFO (First In, First Out) — जे आधी गेलं ते आधी बाहेर येतं. दोन्ही real-world आणि algorithms मध्ये खूप useful आहेत.

Stack — Python list वापरा

python
# Stack operations: push, pop, peek, isEmpty

stack = []

# Push — O(1)
stack.append(1)
stack.append(2)
stack.append(3)
print(stack)     # [1, 2, 3]

# Pop — O(1) — top element काढा
top = stack.pop()
print(top)       # 3

# Peek — top बघा (remove नाही)
print(stack[-1]) # 2

# Check if empty
print(len(stack) == 0)  # False

# Use cases: undo/redo, browser back, function call stack

Valid Parentheses — classic stack problem

python
def is_valid(s):
    stack = []
    pairs = {')': '(', '}': '{', ']': '['}

    for char in s:
        if char in '({[':
            stack.append(char)         # opening bracket push
        elif char in ')}]':
            if not stack or stack[-1] != pairs[char]:
                return False           # mismatch
            stack.pop()                # matching bracket pop

    return len(stack) == 0             # empty असेल तरच valid

print(is_valid("({[]})"))  # True
print(is_valid("({[})"))   # False

Queue — collections.deque वापरा

python
from collections import deque

queue = deque()

# Enqueue — O(1)
queue.append(1)
queue.append(2)
queue.append(3)

# Dequeue — O(1) — front element काढा
front = queue.popleft()
print(front)  # 1

print(queue)  # deque([2, 3])

# Use cases: BFS, task scheduling, print queue

Key Points — लक्षात ठेवा

  • Stack: LIFO — append() / pop()
  • Queue: FIFO — append() / popleft()
  • deque — O(1) operations both ends
  • Valid parentheses — classic stack problem
  • BFS (Graph traversal) — queue वापरतो
0/10 chapters पूर्ण