Edexcel International Advanced Level Computer Science, point 18.2.2
The linked list was described in 14.1.1. In Unit 4 you must write one in code, represented with classes or with references, and handle it with insert, remove, update, find and traverse. Check the PLS for the exact method names.
a. Represent
With classes
Each node is an object, and its next attribute refers to the next node.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None # empty list
With references (parallel lists)
Using two lists: one for the data, one for the "next" indices, with -1 for the end, and a head index.
data = ["B", "C", "A", None] # node contents
nxt = [1, -1, 0, -1] # index of the next node
head = 2 # the list is A -> B -> C
i = head
while i != -1:
print(data[i], end=" ") # A B C
i = nxt[i]
A free list (indices of unused slots) allows nodes to be added and removed. Using references works in languages without objects or pointers, and shows how pointers really work.
b. Handle
Insert
At the front ():
def insert_front(self, data):
node = Node(data)
node.next = self.head
self.head = node
At the end ():
def insert_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
In order (a sorted list):
def insert_sorted(self, data):
node = Node(data)
if self.head is None or data < self.head.data:
node.next = self.head
self.head = node
return
current = self.head
while current.next is not None and current.next.data < data:
current = current.next
# set the new node's link first
node.next = current.next
current.next = node
Remove
def remove(self, target):
previous = None
current = self.head
while current is not None:
if current.data == target:
if previous is None: # removing the head
self.head = current.next
else:
previous.next = current.next
return True
previous = current
current = current.next
return False # not found
Update
Find the node, then change its data.
def update(self, old, new):
current = self.head
while current is not None:
if current.data == old:
current.data = new
return True
current = current.next
return False
Find
def find(self, target):
current = self.head
position = 0
while current is not None:
if current.data == target:
return position # the index in the list
current = current.next
position += 1
return -1
Traverse
def traverse(self):
result = []
current = self.head
while current is not None:
result.append(current.data)
current = current.next
return result
Test and trace
ll = LinkedList()
for x in (30, 10, 20):
ll.insert_sorted(x)
print(ll.traverse()) # [10, 20, 30]
ll.insert_front(5)
ll.insert_end(40)
print(ll.traverse()) # [5, 10, 20, 30, 40]
print(ll.find(20), ll.find(99)) # 2 -1
ll.update(20, 25)
print(ll.remove(5), ll.remove(99)) # True False
ll.remove(40)
print(ll.traverse()) # [10, 25, 30]
Test cases to include:
| Case | Why |
|---|---|
Empty list (traverse, find, remove) |
head is None |
| One item | Removing it empties the list |
| First item | The head pointer must change |
| Last item | next is None |
| Item not present | Methods must not crash |
Common mistakes:
- Losing the rest of the list by changing a pointer before saving the link (insert in the wrong order).
- Forgetting to update
headwhen inserting or removing at the front. - Not checking for
None, giving anAttributeError. - An infinite loop by not moving
currenton.
Worked example
Task: use a linked list to hold a playlist. Add songs, remove one, and show the playlist.
playlist = LinkedList()
for song in ["Intro", "Verse", "Chorus"]:
playlist.insert_end(song)
playlist.insert_front("Overture")
playlist.remove("Verse")
# ['Overture', 'Intro', 'Chorus']
print(playlist.traverse())
Trace of the pointers: after the three insert_end calls: Intro -> Verse -> Chorus. insert_front("Overture"): Overture -> Intro -> Verse -> Chorus (head moves). remove("Verse"): Intro's next is set to Chorus, so Overture -> Intro -> Chorus. No items were shifted.
Exam tip: always handle the special cases (empty list, the head, the last item, not found). Update pointers in the right order (the new node first). Say what you do with head. When tracing, redraw the list with its arrows after each operation.
Check yourself
What two things does each node hold?
A data item and a reference (pointer) to the next node.
What must change when you remove the first node?
The head pointer must be set to the second node (the first node's next).
Why set the new node's next pointer before changing the previous node's pointer?
Otherwise the link to the rest of the list is lost.
How does a linked list represented with references (parallel lists) work?
One list holds the data and another holds the index of the next node (with -1 meaning the end), with a head index marking the start.