A singly linked list stores the nodes A, B, C and D as shown. Each node contains a data value and a pointer to the next node, and head points to node A.
(a) Describe the steps required to delete node C from the list. [3]
(b) State one advantage of a linked list over an array when many deletions and insertions are needed. [1]
- (a) Traverse the list from head, following the pointers, until the node before C (node B) is found (allow: traverse to C while keeping a pointer to the previous node)(1)
- Set the pointer of B to the pointer of C (so B points to D)(1)
- C is now unreachable (no pointer refers to it) so it is removed from the list and its memory can be reclaimed; the list now reads A → B → D(1)
- (b) Items do not need to be shifted along in memory when one is added or removed (only pointers change) (allow: the list grows and shrinks dynamically, so no fixed size has to be declared and no space is pre-allocated)(1)
- Answer: (a) find B, set B.next = C.next (D), C is dereferenced (b) no shifting of elements
- Examiner tip: The key mark is re-pointing the previous node; just 'remove C' scores nothing.