Stacks and queues
Type a value (or leave the box empty for a number) and add it to the stack or the queue. Then take values out and see which one comes first. Both hold 8 items, so you can also cause an overflow (too full) or an underflow (empty).
Stack
Queue
What happened
Stacks: last in, first out
A stack is like a pile of plates: you add to the top (push) and take from the top (pop). The last item added is the first one out (LIFO). Peek looks at the top without removing it. Stacks are behind the Undo button, the Back button in a browser, checking that brackets match, and the call stack that remembers where each function should return to.
Queues: first in, first out
A queue is like a line at a shop: you join at the rear (enqueue) and leave from the front (dequeue). The first item added is the first out (FIFO). Printers, keyboard buffers, messages between programs and the order a web server handles requests all use queues. Breadth-first search uses a queue; depth-first search uses a stack.
Overflow and underflow
If a stack or queue has a fixed size, adding to a full one is an overflow and removing from an empty one is an underflow. Programs must check for both. A famous website for programmers is named after the stack overflow error that happens when functions call themselves too many times.
How they are built
Both can be made with an array. A stack only needs a pointer to the top. A queue needs a front and a rear pointer; a circular queue wraps the rear round to the start of the array so the space freed at the front is reused. Every operation here takes the same time however full it is: O(1).
Questions students ask
What is the difference between a stack and a queue?
A stack is last in, first out (LIFO): the most recently added item is removed first; a queue is first in, first out (FIFO): the item that has waited longest is removed first.
What is stack overflow?
Stack overflow happens when you push onto a stack that is already full; in programs it usually means a function called itself so many times that the call stack ran out of space.
Where are queues used in computers?
Queues are used wherever jobs must be handled in arrival order, such as print jobs, keyboard input, network packets and requests to a web server.
Check yourself
3 quick questions. Tap an answer to see if you are right.
1. A stack is…
Like a pile of plates: you take the top one, which was added last.
2. You enqueue A, B, C, then dequeue once. What comes out?
A queue is first in, first out, so A leaves first.
3. Which uses a stack?
Undo takes back the most recent action first: last in, first out.