Abstract Data Types Using OOP

ADT Linked List

A linked list built from node objects and references — the most pointer-heavy ADT on the syllabus. Each node holds data and a pointer to the next; a head marks the start and a null pointer marks the end. Master the head pointer, the null pointer, the free list, and inserting/deleting by re-routing pointers, and the rest of Paper 4 ADTs feel easy. Covers the object model (Node/LinkedList classes), the Cambridge two-array model, traverse/search, insert/delete, and linked list vs array trade-offs.

28.1 Introduction: The Linked List ADT

A linked list stores a sequence of items where each item, called a node, holds two things: the data and a pointer (a reference) to the next node. A separate head (or start) pointer marks the first node, and the final node's pointer is the null pointer, signalling the end.

Unlike an array, the nodes are not stored in one contiguous block. To insert or delete you simply change a couple of pointers — no shuffling of data. That makes a linked list ideal when the collection grows and shrinks a lot, such as the waiting list at a coaching centre.

TermMeaning
NodeOne element: a data field plus a pointer to the next node.
Head / Start pointerPoints to the first node of the list.
Next pointerThe link from one node to the following node.
Null pointerMarks the end of the list (shown as Ø, None, -1 or 0).
Free listA linked list of unused nodes, ready to be reused.
Free pointerPoints to the first available free node.
TraverseVisit each node in turn by following the next pointers.
Dynamic structureGrows and shrinks at run time without moving data.
Pointer manipulationInserting/deleting by changing links, not by copying data.

28.2 Nodes, the Head & the Null Pointer

Why are we doing this?
  • Every linked-list answer rests on one picture: boxes (nodes) joined by arrows (pointers), starting at the head and ending at null.
  • If you can draw it, you can describe it and code it.

A linked list: head → [10|●] → [20|●] → [30|●] → Ø

head
10
20
30
Ø (null)

Each node carries data and a pointer to the next. The last node points to null.

Key rule — the describe marks To “describe a linked list” Cambridge expects: each node holds data + a pointer to the next node; there is a pointer to the start of the list; the last node has a null pointer; items are added/removed by manipulating pointers (not by moving data); nodes are traversed in sequence; and unused nodes are kept on a free list.

28.3 The Node and LinkedList Classes

Why are we doing this?
  • Python's object references give the cleanest first model: a Node object literally holds a reference to the next Node.
  • This is the version you will run and test.
class Node:
    def __init__(self, data):
        self.data = data       # value stored
        self.next = None       # link to next node

class LinkedList:
    def __init__(self):
        self.head = None       # empty list

    def append(self, data):
        new_node = Node(data)
        if self.head is None:
            self.head = new_node
        else:
            current = self.head
            while current.next:        # walk to the last node
                current = current.next
            current.next = new_node

    def display(self):
        current = self.head
        while current:
            print(current.data, end=" -> ")
            current = current.next
        print("None")

    def search(self, key):
        current = self.head
        while current:
            if current.data == key:
                return True
            current = current.next
        return False

    def delete(self, key):
        current = self.head
        previous = None
        while current and current.data != key:
            previous = current
            current = current.next
        if current is None:
            return "Node not found"
        if previous is None:          # deleting the head
            self.head = current.next
        else:
            previous.next = current.next   # bypass the node

# after append(10), append(20), append(30)
# 10 -> 20 -> 30 -> None
# search(20) -> True   search(40) -> False
# after delete(20)
# 10 -> 30 -> None
Line-by-line explanation
  • Node: Two fields: data and next. A new node always starts with next = None.
  • append: If the list is empty, the new node becomes the head. Otherwise walk to the last node (the one whose next is None) and link the new node there.
  • display: Start at the head, print each node's data, follow next until None.
  • search: Same traversal, but stop and return True the moment the data matches; return False if you reach the end.
  • delete: Walk forward keeping a previous reference. To remove a node, point previous.next past it. Special case: deleting the head just moves head forward.

28.4 The Array Model & the Free List

Why are we doing this?
  • Examiner focus: Paper 3 and Paper 4 almost always present a linked list as two 1D arrays — a Data array and a NextPointer array — with a StartPointer and a FreePointer.
  • You must be able to read the table, follow the pointers, and update them after an insert or delete.

Because exam languages may not have objects, a linked list is simulated with parallel arrays. The index of a node is its “address”. StartPointer holds the index of the first node; each NextPointer holds the index of the following node; the null pointer is a special value (this page uses -1; some papers use 0). Unused indices form the free list, headed by FreePointer.

IndexDataNextPointer
0"Mehrin"-1
1"Adri"2
2"Mohar"0
3free4
4free-1

StartPointer = 1, FreePointer = 3. List order: Adri(1) → Mohar(2) → Mehrin(0) → Ø. Free list: 3 → 4 → Ø. Null pointer = -1. Follow StartPointer=1: index 1 → 2 → 0 → -1 (end).

Exam tip:
  • Watch the null-pointer convention the question gives you.
  • Some papers use 0 for null (so valid indices start at 1); others use -1.
  • Always re-read the stem — do not assume.

28.5 Traversing & Searching

Why are we doing this?
  • Examiner focus: A classic Paper 3 task gives a half-written SearchList function and asks you to complete it.
  • The marks are for starting at the start pointer, looping while not null, comparing the data, and advancing via the next pointer.
FUNCTION SearchList(Item) RETURNS INTEGER
    NullPtr <- -1
    NowPtr  <- StartPointer
    WHILE NowPtr <> NullPtr
        IF LinkList[NowPtr].Data = Item THEN
            RETURN NowPtr          // found: return its index
        ELSE
            NowPtr <- LinkList[NowPtr].NextPtr   // advance
        ENDIF
    ENDWHILE
    RETURN NullPtr                // not found
ENDFUNCTION
Key rule
  • A traversal is always: start at the head pointer → loop while the current pointer is not null → process the node → set current to its next pointer.
  • Forget the final NowPtr ← Next and you get an infinite loop.
Task — Worked Example — Trace SearchList(30)
Trace SearchList(30). List: head → [10|→1] → [20|→2] → [30|→-1] stored at indices 0,1,2; StartPointer=0.
Hint:
  • Start at NowPtr=0; compare data; if no match advance to NextPtr; repeat.
Your Turn — Your Turn — Trace SearchList(99)
Trace SearchList(99) on the same list. What does it return, and how many nodes are visited?
Hint:
  • The loop only ends when NowPtr reaches the null pointer.

28.6 Inserting & Deleting Nodes

Why are we doing this?
  • The whole point of a linked list is that you insert and delete by re-routing pointers, never by shifting data.
  • This is the highest-value skill on the page and a frequent 5–8 mark question.

Insert (take a node from the free list):

To insert, you grab the first free node (at FreePointer), advance the free pointer, write the data, then re-link so the new node sits in the right place. Two pointer changes: the previous node points to the new node, and the new node points to what came next. No data is moved.

PROCEDURE InsertAfter(PrevPtr, NewData)
    IF FreePointer = -1 THEN
        OUTPUT "No free space"
    ELSE
        NewPtr <- FreePointer                       // take a free node
        FreePointer <- LinkList[FreePointer].NextPtr // advance free list
        LinkList[NewPtr].Data <- NewData
        LinkList[NewPtr].NextPtr <- LinkList[PrevPtr].NextPtr
        LinkList[PrevPtr].NextPtr <- NewPtr         // re-link
    ENDIF
ENDPROCEDURE

Delete (return the node to the free list):

Delete by pointing the previous node past the deleted one. The freed node is then linked back into the free list.

Task — Worked Example — Delete a node (not the head)
List indices: 0:"A"→1, 1:"B"→2, 2:"C"→-1, StartPointer=0. Delete "B".
Hint:
  • Find B at index 1; previous is index 0. Bypass: LinkList[0].NextPtr ← LinkList[1].NextPtr. Return node 1 to free list.
Your Turn — Your Turn — Delete the head
Same starting list (A→B→C, StartPointer=0). Delete "A". Which pointer changes, and what is the new StartPointer?
Hint:
  • Deleting the head is the special case: there is no “previous” node.
Key rule
  • Insert: take a node from the free list → advance free pointer → store data → re-link (previous.next → new, new.next → old next).
  • Delete: find the node (tracking previous) → point previous.next past it (or move start if it's head) → return the freed node to the free list.

28.7 Linked List vs Array

Why are we doing this?
  • “Give one advantage and one disadvantage of a linked list compared with an array” is a guaranteed short-answer earner.
  • Know the trade-offs cold.
Linked listArray
Grows/shrinks at run time (dynamic)Usually fixed size
Insert/delete = change a few pointersInsert/delete = shuffle many elements
No direct (random) access — must traverseDirect access by index (fast)
Extra memory for each pointerNo pointer overhead
Exam tip:
  • Advantage: dynamic size / cheap insert & delete by pointer change.
  • Disadvantage: no direct access (must traverse) / extra memory for pointers.
  • These are the standard answers examiners look for.

28.8 Full Exam-Style Question

Paper 3 / Paper 4 · linked list · ~14 marks
  • A waiting list at moshikur.com is held as a linked list using a 1D array of records LinkList.
  • Each record has fields Data and NextPtr.
  • StartPointer indexes the first node, FreePointer indexes the first free node, and the null pointer is -1.

(a) [3] Describe three features of a linked list ADT. (AO1)

(b) [4] Complete the function SearchList(Item) that returns the index of the node containing Item, or -1 if it is not present. (AO2)

FUNCTION SearchList(Item) RETURNS INTEGER
    NowPtr <- ....................
    WHILE NowPtr <> ....................
        IF LinkList[NowPtr].Data = Item THEN
            RETURN ....................
        ENDIF
        NowPtr <- ....................
    ENDWHILE
    RETURN -1
ENDFUNCTION

(c) [5] Write the procedure DeleteNode(Item) that removes the node containing Item by re-routing pointers and returns the freed node to the free list. Assume the node is not the head. (AO3)

(d) [2] State one advantage and one disadvantage of this linked list compared with storing the waiting list in a simple array. (AO1)

Lab Task — Show mark scheme
Reveal the mark scheme for parts (a)–(d).
Hint:
  • (a) 3 from: node = data + pointer; start pointer; last node null; manipulate pointers not data; traverse in sequence; free list.
  • (b) NowPtr ← StartPointer; WHILE NowPtr <> -1; RETURN NowPtr; NowPtr ← LinkList[NowPtr].NextPtr.
  • (c) traverse keeping previous until Data = Item; handle not found; bypass (PrevPtr.NextPtr ← ThisPtr.NextPtr); return to free list (ThisPtr.NextPtr ← FreePointer); FreePointer ← ThisPtr.
  • (d) advantage: dynamic / cheap insert+delete; disadvantage: no direct access / extra memory for pointers.

Key Points Summary

A linked list stores a sequence of items where each node holds data and a pointer (reference) to the next node.
A head (start) pointer marks the first node. The last node's pointer is the null pointer (Ø, None, -1, or 0), signalling the end.
Unlike an array, nodes are NOT stored in one contiguous block. To insert or delete you change a couple of pointers — no shuffling of data.
To "describe a linked list": each node = data + pointer to next; start pointer to first node; last node = null pointer; add/remove by manipulating pointers; traverse in sequence; unused nodes on a free list.
The free list is a linked list of unused nodes, ready to be reused. A free pointer points to the first available free node.
The Node class has two fields: data and next (starts as None). The LinkedList class has head (starts as None for empty).
append: if empty, new node becomes head; else walk to the last node (whose next is None) and link the new node there.
search: start at head, follow next until None, comparing data. Return True on match, False if you reach the end.
delete: walk forward keeping a previous reference. Point previous.next past the deleted node. Special case: deleting the head just moves head forward.
The Cambridge two-array model uses a Data array and a NextPointer array, plus a StartPointer and a FreePointer. The index of a node is its "address".
StartPointer holds the index of the first node. Follow NextPointer from there until the null pointer (-1 or 0) to traverse.
A traversal is always: start at the head pointer → loop while not null → process the node → set current to its next pointer. Forgetting the final advance causes an infinite loop.
SearchList returns the index of the match, or NullPtr (-1) if not found. The null pointer is what stops the loop — not a count.
Insert: take a node from the free list (NewPtr ← FreePointer), advance free pointer, store data, re-link (previous.next → new, new.next → old next). Two pointer changes, no data moved.
Delete: find the node (tracking previous), point previous.next past it (or move start if it's the head), then return the freed node to the free list (ThisPtr.NextPtr ← FreePointer; FreePointer ← ThisPtr).
Advantage over array: dynamic size / cheap insert & delete by pointer change. Disadvantage: no direct access (must traverse) / extra memory for pointers.

28.9 Practice Tasks

Fifteen exam-style tasks. Click Hint for bullet-point guidance, then Help to reveal a worked Python/pseudocode solution.

1Practice Task — Describe a linked list [3 marks]
Describe three features of a linked list ADT.
2Practice Task — Node and LinkedList classes [6 marks]
Write a Node class (data, next) and a LinkedList class with __init__ (head=None) and append (walk to end, link new node).
3Practice Task — display method [3 marks]
Write a display(self) method that prints each node's data followed by " -> ", ending with "None".
4Practice Task — search method [3 marks]
Write a search(self, key) method that returns True if key is in the list, False otherwise.
5Practice Task — delete method (object) [5 marks]
Write a delete(self, key) method that removes the first node with data == key. Handle the head special case. Return "Node not found" if absent.
6Practice Task — Trace SearchList(30) [3 marks]
List: head → [10|→1] → [20|→2] → [30|→-1] at indices 0,1,2; StartPointer=0. Trace SearchList(30). What does it return?
7Practice Task — Trace SearchList(99) [2 marks]
Same list. Trace SearchList(99). What does it return, and how many nodes are visited?
8Practice Task — Pseudocode SearchList [4 marks]
Write Cambridge pseudocode for FUNCTION SearchList(Item) RETURNS INTEGER that returns the index of Item, or -1 if not found.
9Practice Task — Pseudocode InsertAfter [5 marks]
Write Cambridge pseudocode for PROCEDURE InsertAfter(PrevPtr, NewData) that takes a free node, stores data, and re-links.
10Practice Task — Delete a node (not head) [4 marks]
List: 0:"A"→1, 1:"B"→2, 2:"C"→-1, StartPointer=0. Delete "B". Give the pointer changes and the new list.
11Practice Task — Delete the head [3 marks]
Same list (A→B→C, StartPointer=0). Delete "A". Which pointer changes, and what is the new StartPointer?
12Practice Task — Two-array trace [3 marks]
Given StartPointer=1, NextPointer: 1→2, 2→0, 0→-1, what is the visit order?
13Practice Task — Advantage and disadvantage [2 marks]
State one advantage and one disadvantage of a linked list compared with an array.
14Practice Task — Which structure fits? [4 marks]
For each scenario, state linked list or array: (i) frequent inserts/deletes in the middle; (ii) need the 1000th item instantly by index; (iii) size unknown and changes a lot; (iv) memory very tight (no spare for pointers).
15Practice Task — Full exam-style: waiting list [14 marks]
A waiting list uses LinkList with Data, NextPtr, StartPointer, FreePointer (null = -1). (a) Describe 3 features [3]. (b) Complete SearchList(Item) [4]. (c) Write DeleteNode(Item) for non-head node [5]. (d) One advantage + one disadvantage vs array [2].

Question Bank

Answer all questions, then press Submit Quiz to see your score.

0/12 answered

Question 1Multiple Choice

A linked list is a sequence of items where each item (node) holds:

Question 2Multiple Choice

What marks the end of a linked list?

Question 3True / False

In a linked list, items are added/removed by manipulating pointers, not by moving data.

Question 4Multiple Choice

What is a free list?

Question 5Multiple Choice

In the two-array model, what are the two arrays?

Question 6Multiple Choice

In SearchList, what is the loop condition?

Question 7Multiple Choice

How do you advance in SearchList?

Question 8Multiple Choice

When inserting, where do you take the new node from?

Question 9True / False

Deleting the head is a special case because there is no previous node.

Question 10Multiple Choice

After deleting a node, where does the freed node go?

Question 11Multiple Choice

One advantage of a linked list over an array is:

Question 12Multiple Choice

One disadvantage of a linked list vs an array is:

Answer all 12 questions to enable submission.