Stacks and Queues
LIFO and FIFO structures.
A stack is a last-in, first-out (LIFO) collection: you push items onto the top and pop them off the top, like a pile of plates. A queue is first-in, first-out (FIFO): you enqueue at the back and dequeue from the front, like a checkout line. Both restrict access on purpose, which makes them simple, fast and hard to misuse.
Stacks power function calls (the call stack), undo features, bracket matching and depth-first search. Queues schedule print jobs, buffer network data and drive breadth-first search. Both support their main operations in constant time.
Key ideas
- Stack: push, pop, peek at the top, all .
- Queue: enqueue at the back, dequeue at the front, all with a linked list or circular buffer.
- Popping an empty stack is an underflow error; check first.
- A deque allows adding and removing at both ends.
Worked example
Starting empty, a stack does push 3, push 8, pop, push 5, push 1, pop. What is on top, and what would a queue give for the same operations?
- Stack: [3] → [3, 8] → pop 8 → [3, 5] → [3, 5, 1] → pop 1. Top is 5.
- Queue: [3] → [3, 8] → dequeue 3 → [8, 5] → [8, 5, 1] → dequeue 8. Front is 5.
- Same final front value here by coincidence; the removed items differ (8 and 1 versus 3 and 8).
Answer: Stack top ; queue front
Common mistakes
- Mixing up LIFO and FIFO.
- Implementing a queue with an array that shifts on every dequeue, making it .
- Forgetting to check for an empty structure before removing.
Practice questions
Try each one, then open the answer. Numerical answers on this page are verified by an automated calculation check.
1.Push 1, 2, 3 onto a stack, then pop twice. What remains on top?
Show answer
2.Enqueue 1, 2, 3, then dequeue once. Which is at the front?
Show answer
3.Which structure checks matching brackets: stack or queue?
Show answer
A stack