Learn computing fundamentals, programming, algorithms, systems, and software engineering.
A stack is a Last-In-First-Out (LIFO) structure. You can think of it as a stack of plates: the last plate you place on top is the first one you take off. The two core operations are push (add an item) and pop (remove the most recently added item). A queue is the opposite order, First-In-First-Out (FIFO): like a line at a shop, the first person to arrive is the first to be served. Queues support enqueue (add to the back) and dequeue (remove from the front). Stacks show up everywhere in computing. Your program call stack tracks which function is running and where to return to. The undo feature in an editor is a stack of past actions, and matching brackets in code is a classic stack problem. Queues appear wherever work is processed in arrival order: a print queue, an event loop handling requests, or a breadth-first search visiting nodes. In Python you can use a list as a stack, pushing with append and popping with pop. For a queue, the standard list is inefficient because removing from the front shifts every element; the collections.deque is designed for this and gives fast operations at both ends. The key idea to internalize is the ordering guarantee, not the implementation. A stack always returns the most recent item; a queue always returns the oldest. Choosing the wrong one changes the whole behavior of an algorithm.
| Stack | Queue | |
|---|---|---|
| Order | LIFO — last in, first out | FIFO — first in, first out |
| Add | push | enqueue |
| Remove | pop | dequeue |
| Analogy | A stack of plates | A line at a shop |
Only the top of the stack is accessible. Push adds to the top; pop removes from the top.
Items enter at the rear and leave from the front, preserving arrival order.
| Structure | Real-world uses |
|---|---|
| Stack | Undo history, function call stack, bracket matching, browser back button |
| Queue | Print queue, task scheduling, breadth-first search, message buffers |
For a stack use append and pop (both operate on the end). For a queue use append and popleft from collections.deque.
The most recently pushed item is the first one popped.
3 2 1
The first item enqueued is the first one removed.
first second third
Push every opening bracket and pop when you see a matching closing bracket. If the types ever mismatch, the string is invalid.
True False