CIE AS & A Level Computer Science, section 19.1 (Algorithms)
What a linked list is
A linked list holds items in any position in memory, each with a pointer to the next item. The order comes from the pointers, not from the positions.
A linked list can be implemented with two arrays (data and pointers), a start pointer (the first item), and a free list (the unused places) with a free pointer. A pointer of (or 0) marks the end.
| Index | Data | Pointer |
|---|---|---|
| 0 | Ben | 3 |
| 1 | (free) | 4 |
| 2 | Aisha | 0 |
| 3 | Dan | -1 |
| 4 | (free) | -1 |
Start pointer = 2, free pointer = 1. The list in order: Aisha (2), Ben (0), Dan (3).
Operations
Insert a new item: take a place from the free list, put the data in it, and change pointers so it comes in the correct position. No items need to be moved.
Delete: change the pointer of the previous item to skip the deleted one, and add its place to the free list.
data = ["Ben", None, "Aisha", "Dan", None]
nxt = [3, 4, 0, -1, -1]
start, free = 2, 1
def show():
p = start
while p != -1:
print(data[p], end=" ")
p = nxt[p]
print()
show() # Aisha Ben Dan
# insert "Carl" between Ben and Dan
new = free
free = nxt[free] # take the place from the free list
data[new] = "Carl"
nxt[new] = nxt[0] # Carl points to Dan
nxt[0] = new # Ben points to Carl
show() # Aisha Ben Carl Dan
Compared with an array
| Array | Linked list | |
|---|---|---|
| Insert or delete in the middle | items are shifted | only pointers change |
| Access an item | direct, by index | must follow the pointers |
| Memory | no extra | extra for the pointers |
Common mistake: forgetting to update both pointers when inserting: the new item must point to the next item and the previous item must point to the new one. Do these in the correct order, or you lose the rest of the list.
Exam tip: list the items by following the start pointer and each pointer in turn. When inserting or deleting, show which pointers change and the new free list.
Check yourself
What does the start pointer hold?
The index of the first item in the list.
Why is inserting into a linked list quicker than into an array?
Only pointers need to change, so no items have to be shifted.
What is the free list?
A list of unused places in the arrays, from which new items are taken.