CIE AS & A Level Computer Science, section 10.4 (Introduction to Abstract Data Types (ADT))
Linked list
A linked list is an ADT made of nodes. Each node holds an item of data and a pointer to the next node. A head pointer shows the first node, and the last node's pointer is null (it points to nothing).
Compared with an array
| Linked list | Array |
|---|---|
| size can grow and shrink | fixed size |
| items are easy to insert and delete (change pointers) | inserting or deleting means shifting elements |
| can only be read in order from the head | direct access by index |
| needs extra space for pointers | no pointer overhead |
Adding and deleting
- Insert after node X: make the new node's pointer point to X's next node, then make X point to the new node.
- Delete node Y: make the previous node point to the node after Y.
No data is moved: only pointers change.
Implementing with arrays
Use two parallel arrays: one for the data and one for the next pointer, with a head pointer and a free-list pointer to the first unused element.
| Index | Data | Next |
|---|---|---|
| 1 | Ann | 3 |
| 2 | (free) | 4 |
| 3 | Ben | 5 |
| 4 | (free) | 0 |
| 5 | Cal | 0 |
Head = 1, so the list is Ann (1), Ben (3), Cal (5). A pointer of 0 means null.
data = ["Ann", None, "Ben", None, "Cal"]
nxt = [3, 4, 5, 0, 0]
i = 1 # head (1-based)
while i != 0:
print(data[i - 1]); i = nxt[i - 1] # Ann, Ben, Cal
Uses
Where data changes size often, such as a music playlist, or as the basis for stacks, queues and other structures.
Common mistake: moving data when inserting or deleting. In a linked list you change pointers, not the data. Also, when deleting, update the previous node's pointer, and keep track of the head if the first node is removed.
Exam tip: draw the nodes and arrows before and after an insertion or deletion. In an array implementation, show the data, next pointer, head and free list clearly.
Check yourself
What does each node of a linked list contain?
A data item and a pointer to the next node.
How is an item deleted from a linked list?
The pointer of the previous node is changed to point to the node after the deleted one.
Give one advantage of a linked list over an array.
It can grow or shrink easily, and insertion and deletion do not require moving other data.