12. Stacks (LIFO) and Queues (FIFO)
These are abstract data types that restrict how data can be added or removed, making them crucial for certain algorithms.
Stacks (LIFO - Last-In, First-Out)
Think of a stack of plates. The last plate placed on top is the first one removed.
- Operations:
Push: Adds an item to the top (O(1)).Pop: Removes the top item (O(1)).
- Use Cases: Function call management (recursion), undo/redo functionality, expression evaluation.
Queues (FIFO - First-In, First-Out)
Think of people waiting in line. The first person in line is the first one served.
- Operations:
Enqueue: Adds an item to the rear (O(1)).Dequeue: Removes the front item (O(1)).
- Use Cases: Print job scheduling, operating system task management, Breadth-First Search (Graph Algorithms).