impera Open Impera

IB Diploma Computer Science · Computational thinking and problem-solving

Abstract data types (HL)

1What an abstract data type is

An abstract data type (ADT) describes a collection of data by what it does (its operations and their behaviour), not how it is built.

  • A stack is defined by "push, pop, peek, is empty", whatever is used to store the items underneath.
  • The same ADT can be implemented in different ways, for example with an array or a linked list. Code that uses the ADT does not need to change if the implementation does: this is abstraction and encapsulation working together.

Static vs dynamic implementations:

  • A static structure (a fixed-size array) reserves its memory in advance. Fast access by index, but it can fill up (overflow) or waste unused space.
  • A dynamic structure (a linked list) grows and shrinks as needed, using pointers (references) to link items. Memory is used only as required, but each item needs extra space for its pointer and items cannot be reached directly by index.
Check yourself

Which describes an abstract data type?

  • A data type that cannot be used in programs, only in theory

  • Any array of integers, whatever operations it allows

  • A data type that only exists in the Python language

  • Data defined by its operations, independent of how it is built

Show the answer

Data defined by its operations, independent of how it is built

Behaviour, not implementation.

2Stacks

A stack is a LIFO structure: last in, first out, like a pile of plates.

  • push(item): add an item to the top.
  • pop(): remove and return the top item.
  • peek(): look at the top item without removing it.
  • is_empty() (and is_full() for a fixed-size stack).
  • Popping an empty stack is underflow; pushing onto a full stack is overflow.
Worked example

Stack operations

  1. Start empty. push(4), push(7), push(2): the stack is [4, 7, 2] with 2 on top.
  2. pop() returns 2. The stack is [4, 7].
  3. push(9): the stack is [4, 7, 9]. peek() returns 9 and leaves it there.

Uses: the call stack that stores return addresses for subroutines and recursion; the undo feature in editors; the browser's back button; checking that brackets are balanced; evaluating expressions.

Check yourself

Items 5, 8 and 3 are pushed onto an empty stack in that order. What does pop() return?

  • 16

  • 8

  • 5

  • 3

Show the answer

3

Last in, first out.

3Queues

A queue is a FIFO structure: first in, first out, like a line at a shop.

  • enqueue(item): add an item at the rear.
  • dequeue(): remove and return the item at the front.
  • is_empty(), is_full().

In an array, a simple linear queue wastes space: once items are dequeued from the front, those slots are never reused. A circular queue fixes this by letting the rear pointer wrap round to the start of the array: rear = (rear + 1) % size.

Stack and queue: a stack adds and removes at the top; a queue adds at the rear and removes from the front

Uses: print queues; keyboard buffers; scheduling processes on a CPU; handling requests to a web server; breadth-first search of graphs.

Check yourself

Why is a circular queue more efficient than a linear queue in a fixed array?

  • It reuses the slots freed at the front by wrapping round

  • It stores its items in sorted order, so searches are fast

  • It never needs a front pointer, only a rear pointer

  • It is a LIFO structure, so items leave in reverse order

Show the answer

It reuses the slots freed at the front by wrapping round

The rear pointer wraps to the start.

4Linked lists

A linked list is a dynamic sequence of nodes. Each node holds the data and a pointer to the next node. A head pointer marks the first node, and the last node points to null.

  • Insert: create a node and change pointers so it fits into the chain. No items need shifting, unlike an array.
  • Delete: change the previous node's pointer to skip the removed node.
  • Search: follow pointers from the head one by one: $O(n)$, because there is no direct indexing.
  • Doubly linked lists also store a pointer to the previous node, so they can be walked in both directions. Circular linked lists have the last node point back to the head.

A singly linked list: the head points to the first node, and the last node points to null

Worked example

Insert "Cy" between "Bo" and "Di"

  1. Create a new node holding "Cy".
  2. Set the new node's pointer to Bo's current next node (Di).
  3. Set Bo's pointer to the new node.
  4. The order is now Bo → Cy → Di; no other nodes moved. (Doing step 3 before step 2 would lose the link to Di.)
Check yourself

What is a disadvantage of a linked list compared with an array?

  • Inserting an item requires shifting all of the others along by one

  • It cannot store strings, only integers and other simple data types

  • Items cannot be reached directly by index; pointers must be followed

  • It cannot grow in size once it has been created, unlike an array

Show the answer

Items cannot be reached directly by index; pointers must be followed

Searching is O(n).

5Binary trees and binary search trees

A tree is a hierarchical structure of nodes. The top node is the root; nodes with no children are leaves. In a binary tree, each node has at most two children (left and right).

In a binary search tree (BST), for every node, all values in the left subtree are smaller and all values in the right subtree are larger. This makes searching fast: each comparison goes left or right, discarding half the tree if it is balanced, so search is $O(\log n)$. A very unbalanced tree (values inserted in sorted order) becomes like a linked list, $O(n)$.

A binary search tree: every left subtree is smaller and every right subtree is larger

Traversals visit every node in a set order:

  • Pre-order (root, left, right): 50, 30, 20, 40, 70, 60, 80. Used to copy a tree.
  • In-order (left, root, right): 20, 30, 40, 50, 60, 70, 80. On a BST this gives the values in sorted order.
  • Post-order (left, right, root): 20, 40, 30, 60, 80, 70, 50. Used to delete a tree safely.
Worked example

Insert 65 into the tree above

  1. Compare with 50: 65 is larger, go right to 70.
  2. Compare with 70: 65 is smaller, go left to 60.
  3. Compare with 60: 65 is larger, and 60 has no right child.
  4. Insert 65 as the right child of 60.
Check yourself

Which traversal of a binary search tree outputs the values in ascending order?

  • Level-order from the right

  • Pre-order

  • Post-order

  • In-order

Show the answer

In-order

Left, root, right.

6Sets and hash tables

A set stores unique items with no particular order. Main operations: add, remove, check membership, and combine sets with union, intersection and difference. Python's set type gives fast membership tests.

A hash table (as in Python's dict) stores key–value pairs for very fast look-up.

  • A hash function turns a key into an array index, such as key % 7.
  • Look-up, insertion and deletion are on average $O(1)$, whatever the table size.
  • A collision happens when two keys hash to the same index: 15 % 7 = 1 and 22 % 7 = 1.
  • Collisions are handled by chaining (each slot holds a small linked list) or open addressing (step to the next free slot, called linear probing).
  • A good hash function spreads keys evenly; a table that gets too full slows down and is resized.
Check yourself

Keys 15 and 22 are both stored with hash function key % 7. What happens?

  • A collision: both map to index 1, so a strategy is needed

  • Key 22 overwrites the hash function with a new one

  • Both keys are stored at index 0 without any problem

  • The table rejects both keys because they are too large

Show the answer

A collision: both map to index 1, so a strategy is needed

15 % 7 = 22 % 7 = 1.

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