This handout teaches Theme B4, Abstract data types, for the course first assessed in 2027, using Python. The whole theme is Higher Level only (AHL).
Prerequisites: B2 Programming (arrays, stacks, queues, recursion) and B3 Object-oriented programming (classes and references).
8.2
抽象数据类型
English
Why does the structure matter?
A music app holds a playlist of 10 000 songs. Adding a song in the middle of an array means shifting thousands of items along; searching an unsorted list for a title checks them one by one. Choosing a different structure makes both jobs fast. This theme is about those structures.
A line of people is a queue you can see. You join at the back and are served from the front, so whoever waited longest is served first — that is exactly FIFOA pile of books is a stack you can see. You can only add or take a book from the top, so the last one you put on is the first one you take off — that is exactly LIFO
Interface and implementation
An abstract data type 抽象数据类型 (ADT) is defined by the values it holds and the operations on them, not by how it is stored. The stack from B2 is an ADT: push, pop, peek and isEmpty, last in first out. It can be implemented 实现 with an array or with a linked list; code that uses the stack does not need to know which.
Same items, two ADTs: the operations, not the storage, decide the order out
A linked list 链表 is a chain of nodes 节点. Each node holds data and a pointer 指针 (a reference) to the next node. The list is reached through its head 头指针; the last node points to None (null).
class Node:
def __init__(self, data):
self.data = data
self.next = None
To traverse 遍历 the list, follow the pointers from the head until None:
def show(head):
current = head
while current is not None:
print(current.data)
current = current.next
Inserting and deleting
Insert after a node: first point the new node onward, then redirect the old pointer
To insert 31 after the node holding 25 (called prev):
new = Node(31)
new.next = prev.next # step 1: new node points to 40
prev.next = new # step 2: 25 now points to the new node
The order matters: doing step 2 first would lose the pointer to 40 and the rest of the list.
To delete the node after prev: prev.next = prev.next.next. The removed node is no longer reachable, and Python's garbage collector frees its memory.
No items are shifted, so insertion and deletion are $O(1)$ once the position is found; but finding a position means traversing from the head, $O(n)$. There is no index: reading the 500th item takes 500 steps.
Variants
Variant
Each node points to
Advantage
singly linked 单向链表
the next node
least memory
doubly linked 双向链表
the next and the previous node
traverse both ways; delete a node without its predecessor
A binary tree 二叉树 is made of nodes that each have at most two children 子节点, left and right. The top node is the root 根节点; a node with no children is a leaf 叶节点. In a binary search tree 二叉搜索树 (BST), every key in a node's left subtree is smaller than the node's key, and every key in its right subtree is larger.
Built by inserting 50, 30, 70, 20, 40, 60, 80, 35 in that order
Inserting and searching
To insert or find a key, start at the root and go left if the key is smaller, right if larger, until a match or an empty place.
Inserting 35: 35 < 50, go left; 35 > 30, go right; 35 < 40, go left; empty, so 35 becomes the left child of 40.
class TreeNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def contains(node, key):
if node is None:
return False
if key == node.key:
return True
if key < node.key:
return contains(node.left, key)
return contains(node.right, key)
Each comparison drops one subtree, so a balanced 平衡 tree of $n$ keys is searched in $O(\log n)$. Keys inserted already sorted (10, 20, 30, …) make a tree that is a single chain: search becomes $O(n)$, no better than a list.
Traversals
A traversal visits every node once. The three depth-first orders differ in when the node itself is visited:
Three depth-first traversals of a binary tree: pre-order, in-order (sorted order) and post-order
Traversal
Order
For the tree above
pre-order 前序遍历
node, left, right
50, 30, 20, 40, 35, 70, 60, 80
in-order 中序遍历
left, node, right
20, 30, 35, 40, 50, 60, 70, 80
post-order 后序遍历
left, right, node
20, 35, 40, 30, 60, 80, 70, 50
In-order traversal of a BST gives the keys in sorted order. Pre-order copies a tree (insert in that order to rebuild it); post-order deletes one (children before parents).
def in_order(node):
if node is not None:
in_order(node.left)
print(node.key)
in_order(node.right)
A set 集合 holds distinct values with no order: adding a value already present changes nothing. Its main operation is a fast membership test.
a = {"maths", "physics", "cs"}
b = {"cs", "art"}
a | b # union: {"maths", "physics", "cs", "art"}
a & b # intersection: {"cs"}
a - b # difference: {"maths", "physics"}
"art" in a # False
Operation
Result
union 并集
in either set
intersection 交集
in both sets
difference 差集
in the first but not the second
subset
every item of one is in the other
Python sets are built on hash tables, so in is $O(1)$ on average, against $O(n)$ for a list.
A hash table 哈希表 stores key–value pairs in an array. A hash function 哈希函数 turns each key into a slot index, so lookup is $O(1)$ on average under suitable hashing and load assumptions; collisions still require comparisons and worst-case lookup can be $O(n)$. A Python dict is a hash table.
Two keys in one slot is a collision; chaining keeps a list in the slot
With 7 slots and $h(k) = k \bmod 7$: $15 \bmod 7 = 1$, $22 \bmod 7 = 1$, $9 \bmod 7 = 2$, $30 \bmod 7 = 2$.
Collisions
A collision 冲突 happens when two keys hash to the same slot. Two common fixes:
Method
How it works
15, 22, 9, 30 with 7 slots
chaining 链地址法
each slot holds a linked list of items
slot 1: 15 → 22; slot 2: 9 → 30
linear probing 线性探测
try the next slot until an empty one
15 → 1; 22 → 2; 9 → 3; 30 → 4
With linear probing, a search for 30 starts at slot 2 and steps on until it finds 30 or an empty slot.
A good hash function is fast and spreads keys evenly. The load factor 负载因子 is $\dfrac{\text{items}}{\text{slots}}$; as it rises, collisions grow, so the table is enlarged and every key rehashed.
Explain what is meant by an abstract data type, using a queue as the example.
A linked list holds 8 → 14 → 21 → None. Write the two statements that insert a node holding 17 after the node p that holds 14, in the correct order.
Explain why reading the $k$th item is slower in a linked list than in an array.
Give one use of a circular linked list.
Draw the BST made by inserting 40, 20, 60, 10, 30, 50, 70, 25.
For your tree in question 5, give the pre-order, in-order and post-order traversals.
State the number of comparisons needed to find 25 in your tree.
Explain what happens to search time if the keys 10, 20, 30, 40, 50 are inserted into a BST in that order.
$A = \{1, 3, 5, 7\}$ and $B = \{3, 4, 5\}$. State $A \cup B$, $A \cap B$ and $A - B$.
Insert the keys 12, 19, 5, 26 into a hash table of 7 slots with $h(k) = k \bmod 7$, using linear probing. State the slot of each key.
Explain why a hash table becomes slower as its load factor rises.
Answers.
An ADT is defined by its values and operations, not by its storage. A queue is defined by enqueue at the rear and dequeue from the front (FIFO), and can be built from an array or a linked list without changing the code that uses it.
new.next = p.next then p.next = new, where new = Node(17).
A linked list has no index: the program must follow the pointers from the head, $k$ steps. An array computes the item's address directly.
E.g. giving each player a turn in a game, or round-robin scheduling of processes.
Root 40; 20 left, 60 right; 10 and 30 under 20; 50 and 70 under 60; 25 the left child of 30.