impera Open Impera

A levels Computer Science · Programming and data

Stacks, queues, trees and graphs

1Stacks

A stack is a last in, first out (LIFO) structure. Items are added and removed at the top only.

A stack. Push and pop both happen at the top, so the last item in is the first out.

OperationEffect
push(x)add x to the top (error if full: stack overflow)
pop()remove and return the top item (error if empty: stack underflow)
peek()return the top item without removing it
isEmpty()check whether the stack is empty

Uses: the call stack for subroutines, undo in editors, the browser back button, and evaluating expressions in reverse Polish notation.

Check yourself

Push 3, push 8, pop, push 5, pop. What is returned by the last pop?

  • Nothing

  • 8

  • 3

  • 5

Show the answer

5

Last in, first out.

2Queues

A queue is first in, first out (FIFO). Items join at the rear and leave from the front.

  • A linear queue in an array wastes space at the front as items leave.
  • A circular queue wraps round: rear = (rear + 1) MOD size, so freed slots are reused.
  • A priority queue removes the item with the highest priority first.

A circular queue of size 8 holding A to E. The front is at index 5 and the rear has wrapped round to index 1.

Uses: print queues, keyboard buffers, and processes waiting for the CPU.

Check yourself

In a circular queue of size 8, rear is at index 7. Where does the next item go?

  • Index 0

  • Index 8

  • Index 7

  • Index 1

Show the answer

Index 0

(7 + 1) MOD 8.

3Trees and binary search trees

A tree is a connected graph with no cycles. It has a root, and each node has children; nodes with no children are leaves.

In a binary search tree (BST), each node has at most two children: everything in the left subtree is smaller, and everything in the right subtree is larger.

A binary search tree built from 50, 30, 70, 20, 40, 60, 80. Each comparison halves the part of the tree left to search.

Worked example

Building a BST

  1. Insert 50, 30, 70, 20, 40, 60, 80 in that order.
  2. 50 is the root; 30 < 50 goes left; 70 > 50 goes right.
  3. 20 < 50, then 20 < 30, so it is the left child of 30. The rest follow the same rule.
  4. Searching for 60 takes 3 comparisons (50, 70, 60) instead of up to 7.

A balanced BST is searched in O(log n) time. If items are inserted in sorted order, the tree becomes a long chain and searching falls to O(n).

Check yourself

In a BST, where is a value smaller than the root placed?

  • At the end of the tree

  • In the right subtree

  • As the new root

  • In the left subtree

Show the answer

In the left subtree

Left is smaller.

4Graphs

A graph is a set of vertices (nodes) joined by edges (arcs).

  • Undirected: edges work both ways. Directed: edges have a direction.
  • Weighted: each edge has a value, such as distance or cost.
  • Graphs model road maps, social networks, computer networks and web links.

An undirected weighted graph with 5 vertices and 6 edges. The adjacency matrix and list below store the same graph.

Check yourself

Which kind of graph would model one-way streets?

  • A tree

  • A stack

  • An undirected graph

  • A directed graph

Show the answer

A directed graph

Edges with direction.

5Representing graphs

An adjacency matrix is a grid where entry [i][j] is the edge weight (or 0 / blank if there is no edge). An adjacency list stores, for each vertex, a list of its neighbours.

The graph above as an adjacency matrix:

ABCDE
A–42––
B4–15–
C21–8–
D–58–3
E–––3–

As an adjacency list: A: B(4), C(2); B: A(4), C(1), D(5); C: A(2), B(1), D(8); D: B(5), C(8), E(3); E: D(3).

Adjacency matrixAdjacency list
quick to check whether an edge existsuses less memory for sparse graphs
wastes memory when there are few edgesslower to check a single edge
good for dense graphsgood for sparse graphs
Check yourself

Why is an adjacency list better for a graph with 1000 vertices and 1200 edges?

  • Lists can only store directed graphs, which are more common

  • Matrices cannot store edge weights, so a list is the only option

  • The graph is sparse, so a matrix would waste a lot of memory

  • Lists are always faster than matrices, whatever the graph's density

Show the answer

The graph is sparse, so a matrix would waste a lot of memory

Few edges.

6Choosing a structure

StructureOrderTypical use
stackLIFOundo, recursion, back button
queueFIFObuffers, scheduling
priority queueby priorityDijkstra's algorithm, A&E triage
binary search treesortedfast search, insert and delete
graphany linksmaps, networks

Stacks and queues are abstract data types: they are defined by their operations, and can be built from an array or a linked list.

Check yourself

What is meant by an abstract data type?

  • A built-in integer type provided by the language

  • A type defined by its operations, not by how it is stored

  • A type that has no values stored in it

  • A data type that only exists in mathematics

Show the answer

A type defined by its operations, not by how it is stored

What, not how.

Now test yourself

This lesson has a 8-question quiz and 5 exam-style questions with mark schemes in Impera. Free, with your progress saved.

Practise in Impera