Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Stacks and queues

After this lesson: I can use a stack and a queue to solve a problem.

50 min lesson3 commandsCompilers and computer architecture lab: gcc, flex, bison and RISC-V in one VM

What are a stack and a queue?

A stack is a pile where you always take the newest item first. A queue is a line where you always take the oldest item first.

Your editor's undo button uses a stack, and a shared printer uses a queue. A compiler uses a stack to check that every bracket in your code is closed.

By the end of this lesson

Note

I can use a stack and a queue to solve a problem.

Key words

WordWhat it meansExample
Stacka collection where the newest item leaves first
Queuea collection where the oldest item leaves first
Pushput an item on top of a stackstack.append(3)
Poptake the top item off a stackstack.pop()
LIFOlast in, first out: the rule of a stack
FIFOfirst in, first out: the rule of a queue

The cells students fill in are left blank in this preview.

A stack removes the newest item first

A stack has two jobs. Push puts an item on top. Pop takes the top item off and gives it back.

This is LIFO, last in, first out. A pile of plates works the same way: you only reach the top plate. With a Python list, append pushes and pop() pops, and both work at the cheap end.

Worked example: an undo history

ActionStack (top on the right)Item returned
Type "a"aNone
Type "b"a bNone
Type "c"a b cNone
Undoa bc
Undoab

The cells students fill in are left blank in this preview.

Push two items and pop one

Command
python3 -c "s = []; s.append(1); s.append(2); print(s.pop(), s)"

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

Read three lines newest first

Command
printf 'one\ntwo\nthree\n' | tac

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

A queue removes the oldest item first

A queue also has two jobs. Enqueue adds an item at the back. Dequeue removes the item at the front.

This is FIFO, first in, first out, like people waiting at a till. A print queue sends jobs to the printer in the order they arrived.

Worked example: a print queue

EventQueue (front on the left)Printed
Ana sends report.pdfreport.pdfNothing
Ben sends slides.pdfreport.pdf slides.pdfNothing
Printer takes a jobslides.pdfreport.pdf
Cai sends notes.pdfslides.pdf notes.pdfNothing
Printer takes a jobnotes.pdfslides.pdf

The cells students fill in are left blank in this preview.

A list is a poor queue

A list is cheap at its end only. Removing the front of a list shifts every item, as the last lesson showed.

Python's deque (say "deck") is built for both ends. append adds at the back and popleft removes from the front, and neither shifts anything.

Add to the back, remove from the front

Command
python3 -c "from collections import deque; q = deque(['a', 'b']); q.append('c'); print(q.popleft(), list(q))"

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

A common mistake

Warning

Many people mix up the two orders and think a stack and a queue behave alike. They do not. A stack gives back the newest item. A queue gives back the oldest. Ask which item must leave next: if it is the one that arrived last, you need a stack.

A stack checks that brackets match

Read the text from left to right. Push every opening bracket. For a closing bracket, pop the top and see whether it matches.

If the stack is empty at a closer, or the kinds differ, the text is wrong. If anything is left on the stack at the end, a bracket was never closed.

Worked example: checking {[()]}

CharacterActionStack afterwards
{Push{
[Push{ [
(Push{ [ (
)Pop ( and match{ [
]Pop [ and match{
}Pop { and matchEmpty: correct

The cells students fill in are left blank in this preview.

Find the missing bracket

Code: python
# Check brackets with a stack: push an opener, pop on a closer.
text = "square(7) + (3"
stack = []
ok = True
for ch in text:
    if ch == "(":
        stack.append(ch)
    elif ch == ")":
        if len(stack) == 0:
            ok = False
        else:
            stack.pop()
if len(stack) > 0:
    ok = False
print(ok, len(stack))
# Change text to "square(7) + (3)" and run again.

About this lab and its source: Compilers and computer architecture lab: gcc, flex, bison and RISC-V in one VM

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.