Stacks and Queues
LIFO vs FIFO โ two simple structures behind undo buttons, browsers, and task schedulers.
Stack (LIFO)
A stack follows Last In, First Out โ the last element added is the first one removed. Main operations: push (add to top), pop (remove from top), peek (view top without removing). Think of a stack of plates โ you always take from the top.
int stack[100], top = -1;
void push(int x) { stack[++top] = x; }
int pop() { return stack[top--]; }Queue (FIFO)
A queue follows First In, First Out โ the first element added is the first one removed. Main operations: enqueue (add to rear), dequeue (remove from front). Think of a line at a ticket counter โ first person in line gets served first.
Where They're Used
Stacks: function call management (call stack), expression evaluation, undo/redo. Queues: task scheduling, printer queues, handling requests in the order they arrive (BFS traversal in graphs).
๐ Real-World Use
Your browser's Back button uses a stack of visited pages. Customer support ticket systems use a queue so requests are handled in the order they were received (first come, first served).
๐ก Pro Tip
A very common interview question is 'implement a queue using two stacks' โ practice this, it tests whether you truly understand both structures, not just memorized definitions.
๐งช Quick Self-Test
Check what you just learned โ no pressure, just practice.
1. A stack follows which order?
2. Which structure would you use for a printer queue?