OCR H446, section 1.4.2 (c)
For each structure in 1.4.2 (b), you need to know how to create it, traverse it (visit each item), add data and remove data. This can be done using arrays and procedural code, or with an object-oriented approach (classes). The Python examples below use both.
Stack
Using an array and a pointer
size = 5
stack = [None] * size
top = -1 # -1 means empty
def push(item):
global top
if top == size - 1:
print("Stack full") # overflow
else:
top = top + 1
stack[top] = item
def pop():
global top
if top == -1:
print("Stack empty") # underflow
return None
item = stack[top]
top = top - 1
return item
push(4); push(9); push(1)
print(pop(), pop()) # 1 9
- Create: an array and a top pointer at .
- Add (push): check it isn't full, increase the pointer, store the item.
- Remove (pop): check it isn't empty, read the item, decrease the pointer.
- Traverse: from
topdown to 0 (the top item first).
Queue
Circular queue using an array
class CircularQueue:
def __init__(self, size):
self.items = [None] * size
self.size = size
self.front = 0
self.count = 0
def enqueue(self, item):
if self.count == self.size:
print("Queue full")
return
rear = (self.front + self.count) % self.size
self.items[rear] = item
self.count += 1
def dequeue(self):
if self.count == 0:
print("Queue empty")
return None
item = self.items[self.front]
self.front = (self.front + 1) % self.size
self.count -= 1
return item
- Add (enqueue): at the rear, wrapping round with
% size. - Remove (dequeue): from the front, then move the front on.
- Traverse: from the front,
countitems, wrapping round.
Linked list
Using nodes (object-oriented)
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def add_front(self, data):
node = Node(data)
node.next = self.head
self.head = node
def add_end(self, data):
node = Node(data)
if self.head is None:
self.head = node
return
current = self.head
while current.next is not None:
current = current.next
current.next = node
def remove(self, data):
current = self.head
previous = None
while current is not None:
if current.data == data:
if previous is None:
self.head = current.next # removing the first
else:
previous.next = current.next
return
previous = current
current = current.next
def traverse(self):
current = self.head
while current is not None:
print(current.data)
current = current.next
- Create: a list with
head = None(empty). - Traverse: start at
head, and follownextuntil it isNone. - Add at the front: the new node points to the old head, and becomes the head.
- Add at the end: traverse to the last node, then link the new node.
- Remove: find the node, and make the previous node skip it by pointing to the node after it. If it is the head, move the head.
Using an array (the form exam questions often use)
A linked list can also be stored in an array (or a table). Each element holds the data and the index of the next node (its pointer). A start pointer gives the first node, and a null pointer marks the end. The nodes don't have to be in order in the array: the pointers give the order.
start = 1
| Index | Data | Next |
|---|---|---|
| 0 | Kiwi | 3 |
| 1 | Apple | 2 |
| 2 | Fig | 0 |
| 3 | Pear | null |
| 4 | ||
| 5 |
Following the pointers from index 1: Apple (1), Fig (2), Kiwi (0), Pear (3), then null, so the list is in alphabetical order.
data = ["Kiwi", "Apple", "Fig", "Pear", None, None]
nxt = [3, 2, 0, None, None, None]
start = 1 # Apple is first
def traverse():
p = start
while p is not None: # None marks the end (null)
print(data[p])
p = nxt[p]
def add_in_order(item, free):
global start
data[free] = item
previous = None
p = start
while p is not None and data[p] < item:
previous = p
p = nxt[p]
nxt[free] = p # the new node points to its successor
if previous is None:
start = free # new first item
else:
nxt[previous] = free # the predecessor points to the new node
def remove(item):
global start
previous = None
p = start
while p is not None and data[p] != item:
previous = p
p = nxt[p]
if p is None:
return # not found
if previous is None:
start = nxt[p] # removing the first item
else:
nxt[previous] = nxt[p] # the predecessor skips the node
data[p] = None # the slot is free again
Adding Grape in order, using the free slot 4: Grape belongs between Fig and Kiwi, so Grape's pointer is set to 0 (Kiwi), and Fig's pointer is changed from 0 to 4.
Removing Kiwi (index 0): its predecessor, Grape, takes Kiwi's pointer, so Grape now points to 3 (Pear). Kiwi is skipped, and slot 0 becomes free to reuse. Removing the first node moves the start pointer instead.
| Index | Data | Next (after adding Grape) | Next (after removing Kiwi) |
|---|---|---|---|
| 0 | Kiwi | 3 | (free) |
| 1 | Apple | 2 | 2 |
| 2 | Fig | 4 | 4 |
| 3 | Pear | null | null |
| 4 | Grape | 0 | 3 |
Real implementations often keep the free slots in a free list too, with a free pointer to the next one available.
Graph
Adjacency list (a dictionary)
graph = {}
def add_vertex(v):
if v not in graph:
graph[v] = []
def add_edge(a, b): # undirected
graph[a].append(b)
graph[b].append(a)
def remove_edge(a, b):
graph[a].remove(b)
graph[b].remove(a)
add_vertex("A"); add_vertex("B"); add_vertex("C")
add_edge("A", "B"); add_edge("A", "C")
- Create: an empty dictionary (or a 2D array for an adjacency matrix).
- Add: a vertex, then edges between vertices. For a directed graph, add the edge in one direction only.
- Remove: edges first, and then the vertex.
- Traverse: depth-first (using a stack) or breadth-first (using a queue):
def breadth_first(graph, start):
visited = [start]
queue = [start]
while queue:
v = queue.pop(0)
print(v)
for n in graph[v]:
if n not in visited:
visited.append(n)
queue.append(n)
Binary search tree
class TreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(node, value):
if node is None:
return TreeNode(value)
if value < node.value:
node.left = insert(node.left, value)
else:
node.right = insert(node.right, value)
return node
def in_order(node):
if node is not None:
in_order(node.left)
print(node.value)
in_order(node.right)
root = None
for v in [8, 3, 10, 1, 6, 14]:
root = insert(root, v)
in_order(root) # 1 3 6 8 10 14
- Create: a root node (or
Nonefor an empty tree). - Add: compare with each node, going left if smaller and right if larger, until an empty place is found.
- Traverse: in-order (left, node, right) gives sorted order. Pre-order (node, left, right) copies the tree, and post-order (left, right, node) visits children before parents (see 2.3.1 (e)).
- Remove: there are three cases:
- A leaf: just remove it.
- One child: replace the node with its child.
- Two children: replace its value with the smallest value in its right subtree (the in-order successor), then remove that node.
Hash table
size = 7
table = [None] * size
def hash_key(key):
return sum(ord(c) for c in key) % size
def add(key, value):
i = hash_key(key)
while table[i] is not None: # collision: linear probing, try the next slot
i = (i + 1) % size
table[i] = (key, value)
def find(key):
i = hash_key(key)
count = 0
while table[i] is not None and count < size:
if table[i][0] == key:
return table[i][1]
i = (i + 1) % size
count += 1
return None
- Create: an array of empty slots.
- Add: work out the hash, and use that slot. If it is taken (a collision), try the next free one.
- Find: go to the hashed slot, and follow the same collision rule until the key is found or an empty slot shows that it isn't there.
- Remove: needs care. Simply emptying a slot can break the chain for other keys that were placed after it, so the slot is often marked as deleted.
- Traverse: loop through every slot, skipping the empty ones (the order is not meaningful).
Summary of operations
| Structure | Add | Remove | Traverse |
|---|---|---|---|
| Stack | Push on top | Pop from top | Top to bottom |
| Queue | Enqueue at rear | Dequeue from front | Front to rear |
| Linked list | At the front or end, by changing pointers | Bypass the node | Follow the pointers |
| Graph | Add a vertex, then edges | Remove edges, then the vertex | Depth-first or breadth-first |
| BST | Go left or right to an empty place | Three cases | In-order, pre-order, post-order |
| Hash table | Hash the key (handle collisions) | Find, then clear or mark | Visit each slot |
Worked example
Task: show the stack after each step: push 5, push 8, pop, push 2, pop, pop. What is returned?
| Step | Operation | Returned | Stack (bottom to top) |
|---|---|---|---|
| 1 | push 5 | 5 | |
| 2 | push 8 | 5, 8 | |
| 3 | pop | 8 | 5 |
| 4 | push 2 | 5, 2 | |
| 5 | pop | 2 | 5 |
| 6 | pop | 5 | (empty) |
Another pop now would cause stack underflow.
Exam tip: for each operation, mention the checks (full or empty), and how the pointers change. For a BST, state the rule (smaller left, larger right). For linked lists, say that the previous node's pointer is changed, so the node is bypassed.
Check yourself
How do you remove a node from the middle of a linked list?
Find the node, then change the pointer of the previous node so that it points to the node after the one being removed, bypassing it.
What does an in-order traversal of a binary search tree produce?
The values in sorted (ascending) order.
What condition must be checked before pushing onto an array-based stack?
That the stack isn't full, otherwise there would be stack overflow.
How is a collision handled when adding to a hash table with linear probing?
The item is placed in the next free slot, wrapping round to the start if necessary.