Singly Linked Lists: Diagrams, Algorithms and Array-Based Nodes in C

UNIT 2 • MODULE 1 • LESSON 06

Arrays are wonderful when you know how many items you have and you rarely insert in the middle. But think about keeping a class register in alphabetical order. Every time a new student joins, everyone after the new name must shift down one place to make room. With a thousand names, that is a lot of shifting.

A linked list solves this a different way. Instead of relying on items sitting next to each other in memory, each item carries a link to the item that follows it. To insert a new name, you just change two links. Nothing else moves. In this lesson you will learn the singly linked list as an ADT, draw it and trace it, write its algorithms in pseudocode, and see a C version that stores nodes inside arrays so you can watch every link.

What you will learn

  • What nodes, links, head and NULL are in a singly linked list.
  • How to draw linked list diagrams and trace operations on them.
  • Algorithms for traversal, search, insert at the front, insert in order and delete.
  • How a linked list can be stored in two parallel arrays (data and next) with a free list.
  • A C program that builds, prints and edits an array-based linked list.
  • How linked lists compare with arrays, and where they are used.

Part 1: Nodes, links and head

A singly linked list is a linear ADT made of nodes. Each node has two parts:

  • a data field holding the item (a number, a name, or a whole record), and
  • a next field (also called a link or pointer) holding the location of the following node.

A separate variable called head (sometimes start) holds the location of the first node. The last node’s next field holds a special value, NULL (or NIL), meaning “there is no next node”. An empty list is simply one where head itself is NULL. It is called singly linked because each node links in one direction only: forwards.

A singly linked list: data | nexthead122540NULLInsert 30 after 25122540NULL30step 2step 1
Step 1: the new node copies 25’s link, so it points to 40. Step 2: 25 is changed to point to the new node. The old link (dashed) is replaced.

The diagram also shows why linked lists are good at insertion. To put 30 between 25 and 40, you make the new node point to 40, then change 25 so it points to the new node. Two links change, and no data moves. The order of those two steps matters: if you changed 25’s link first, you would lose the only route to 40 and the rest of the list.

FeatureArraySingly linked list
How order is keptBy position in memoryBy links between nodes
Access the 50th itemDirect: a[49]Follow 49 links from head
Insert in the middleShift later itemsChange two links
Delete from the middleShift later items backChange one link
SizeFixed when declared (in C)Can grow while free nodes or memory remain
Extra storageNoneOne link per node
SearchLinear, or binary if sortedLinear only

Part 2: Linked list algorithms

All linked list algorithms are built from one move: follow the link. Use a variable, often called current, that starts at head and repeatedly becomes current.next until it reaches NULL.

Traverse (print every item)

PROCEDURE printList()
    current ← head
    WHILE current ≠ NULL DO
        OUTPUT current.data
        current ← current.next
    ENDWHILE
END PROCEDURE

Search

FUNCTION search(target)
    current ← head
    WHILE current ≠ NULL DO
        IF current.data = target THEN
            RETURN current
        ENDIF
        current ← current.next
    ENDWHILE
    RETURN NULL
END FUNCTION

Search on a linked list is always a linear search: even if the data is sorted, you cannot jump to the middle, because the only way to reach a node is to follow links from head. You will compare linear and binary search in Lesson 07.

Insert at the front

PROCEDURE insertFront(value)
    newNode ← get a free node
    newNode.data ← value
    newNode.next ← head
    head ← newNode
END PROCEDURE

Insert in order (sorted list)

PROCEDURE insertOrdered(value)
    newNode ← get a free node
    newNode.data ← value
    IF head = NULL OR value < head.data THEN
        newNode.next ← head
        head ← newNode
    ELSE
        prev ← head
        WHILE prev.next ≠ NULL
              AND prev.next.data < value DO
            prev ← prev.next
        ENDWHILE
        newNode.next ← prev.next
        prev.next ← newNode
    ENDIF
END PROCEDURE

Delete a value

PROCEDURE deleteValue(value)
    prev ← NULL
    current ← head
    WHILE current ≠ NULL
          AND current.data ≠ value DO
        prev ← current
        current ← current.next
    ENDWHILE
    IF current = NULL THEN
        OUTPUT "Not found"
    ELSE IF prev = NULL THEN
        head ← current.next
    ELSE
        prev.next ← current.next
    ENDIF
    return current to the free nodes
END PROCEDURE

Notice the two special cases that appear again and again: the list might be empty (head = NULL), and the node you want might be the first one, in which case head itself must change. Good linked list answers always handle both.

Part 3: Try it

The animator stores up to six nodes in two arrays, exactly like the C program in Part 5. The top shows the list as a chain of boxes (data | next slot); the table underneath shows what is really in memory. Pick a value, then choose an operation.

Try it 1Linked list animator (nodes stored in arrays)

Choose a value, then an operation. Watch which links change. Complete the four challenges.

Value

Look at the memory table after a few inserts and deletes. The slots are rarely in list order. Slot 3 might come first and slot 0 last. That is fine: the order lives in the links, not in the slot numbers.

Part 4: Storing a linked list in arrays

In C, linked lists are usually built with pointers and memory allocated while the program runs. CAPE exam questions focus on diagrams and algorithms, so in this lesson we use a simpler model that shows exactly the same ideas: two parallel arrays. data[i] holds a node’s item and next[i] holds the slot number of the following node, with -1 standing for NULL. head is just an integer slot number.

Unused slots are kept on a second chain called the free list. At the start, every slot is free: slot 0 links to 1, 1 to 2, and so on, and freeHead is 0. To get a node, take the slot at freeHead and move freeHead along its link. To return a node after deleting it, push it back onto the front of the free list. This is how the list can grow and shrink inside a fixed block of memory without ever shifting data.

Step through two short programs that use this model. The variables show both arrays, head and freeHead.

Try it 2Trace an array-based linked list

Choose a program, then step through it. Predict which links change before you reveal them.

Output


Part 5: The C version

Worked example 1: build, delete and reuse

This program inserts 40, 10, 30 and 20 in order, prints the list, deletes 30, tries to delete a value that is not there, then inserts 25. Finally it prints the raw arrays so you can see where each node really lives.

#include <stdio.h>

#define MAX 5
#define NIL -1

int data[MAX];
int next[MAX];
int head = NIL;
int freeHead = 0;

void initList(void)
{
    int i;
    for (i = 0; i < MAX - 1; i++)
        next[i] = i + 1;
    next[MAX - 1] = NIL;
}

int getNode(void)
{
    int n = freeHead;
    if (n != NIL)
        freeHead = next[n];
    return n;
}

void insertOrdered(int value)
{
    int n = getNode(), p;
    if (n == NIL) {
        printf("List full: %d\n", value);
        return;
    }
    data[n] = value;
    if (head == NIL || value < data[head]) {
        next[n] = head;
        head = n;
        return;
    }
    p = head;
    while (next[p] != NIL
           && data[next[p]] < value)
        p = next[p];
    next[n] = next[p];
    next[p] = n;
}

void deleteValue(int value)
{
    int p = NIL, n = head;
    while (n != NIL && data[n] != value) {
        p = n;
        n = next[n];
    }
    if (n == NIL) {
        printf("%d not found\n", value);
        return;
    }
    if (p == NIL)
        head = next[n];
    else
        next[p] = next[n];
    next[n] = freeHead;
    freeHead = n;
}

void printList(void)
{
    int n = head;
    printf("head");
    while (n != NIL) {
        printf(" -> %d", data[n]);
        n = next[n];
    }
    printf(" -> NULL\n");
}

int main(void)
{
    int i;

    initList();
    insertOrdered(40);
    insertOrdered(10);
    insertOrdered(30);
    insertOrdered(20);
    printList();
    printf("head=%d next[head]=%d\n",
           head, next[head]);
    deleteValue(30);
    deleteValue(99);
    printList();
    insertOrdered(25);
    printList();
    printf("slot data next\n");
    for (i = 0; i < 4; i++)
        printf("%4d %4d %4d\n",
               i, data[i], next[i]);
    return 0;
}

Output:

head -> 10 -> 20 -> 30 -> 40 -> NULL
head=1 next[head]=3
99 not found
head -> 10 -> 20 -> 40 -> NULL
head -> 10 -> 20 -> 25 -> 40 -> NULL
slot data next
   0   40   -1
   1   10    3
   2   25    0
   3   20    2

The values arrived in the order 40, 10, 30, 20, so they sit in slots 0, 1, 2 and 3 in that order, yet the list prints in sorted order because the links were set by insertOrdered. head is 1 (the slot holding 10), and next[head] is 3 (the slot holding 20). When 30 was deleted, slot 2 went back to the free list; the next insert (25) reused slot 2. The final table shows that 25 in slot 2 links to slot 0, which holds 40, whose next is -1 (the end).

The C code uses && in its while conditions, just like the AND in the pseudocode. C evaluates && left to right and stops as soon as the result is known, so next[p] != NIL && data[next[p]] < value never reads data[-1]: if the first test is false, the second is skipped.

Worked example 2: walking a list that is already built

#include <stdio.h>

#define NIL -1

/* A list already built in two arrays:
   head is slot 2, so the order is
   2 -> 0 -> 3 -> 1 -> NULL           */
int data[4] = {17, 42, 8, 23};
int next[4] = {3, NIL, 0, 1};
int head = 2;

int length(void)
{
    int n = head, count = 0;
    while (n != NIL) {
        count++;
        n = next[n];
    }
    return count;
}

int search(int target, int *visits)
{
    int n = head;
    *visits = 0;
    while (n != NIL) {
        (*visits)++;
        if (data[n] == target)
            return n;
        n = next[n];
    }
    return NIL;
}

int main(void)
{
    int v, slot;

    printf("Length: %d\n", length());
    slot = search(23, &v);
    printf("23: slot %d, %d visits\n",
           slot, v);
    slot = search(5, &v);
    printf("5: slot %d, %d visits\n",
           slot, v);
    return 0;
}

Output:

Length: 4
23: slot 3, 3 visits
5: slot -1, 4 visits

Here the arrays were filled in directly. Start at head = 2 (value 8), then follow next: slot 0 (17), slot 3 (23), slot 1 (42), then -1. Finding 23 takes three visits. Searching for 5 visits all four nodes before reaching the end, then returns -1 for "not found". Both length and search have exactly the same shape as the printList pseudocode: start at head, follow next until NULL.

A glimpse of the pointer version

With pointers, each node is a struct allocated while the program runs, and next holds a memory address instead of a slot number:

typedef struct Node {
    int data;
    struct Node *next;
} Node;

The algorithms are identical: current = current->next replaces n = next[n], and NULL replaces -1. Getting a node uses malloc and returning it uses free, which play the same role as the free list. If you can trace the array version, you understand the pointer version too.

Part 6: Uses and variations

  • Ordered registers and directories: names can be kept in order with cheap insertions and deletions.
  • Stacks and queues without a fixed size: a linked stack pushes and pops at head; a linked queue adds at a tail node and removes at head. No overflow until memory runs out.
  • Playlists and image viewers: "next track" is literally following a link.
  • Memory management: operating systems keep free blocks of memory on linked free lists, just like freeHead in this lesson.
  • Variations: a doubly linked list adds a link to the previous node, so you can move backwards; a circular linked list makes the last node point back to the first.

Try it 3Linked list drill

Pick a mode. "Follow" gives you data and next arrays and asks you to follow the links. "Rules" checks linked list facts.

Summary

IdeaRemember
NodeData plus a link (next) to the following node.
head and NULLhead finds the first node; NULL (-1 in our arrays) ends the list.
Traverse or searchcurrent ← head; follow next until NULL. Always linear.
Insert at frontnew.next ← head, then head ← new.
Insert after prevnew.next ← prev.next, then prev.next ← new (this order).
DeleteFind prev; prev.next ← current.next (or head ← current.next for the first node).
Array modeldata[], next[], head, and a free list of unused slots.

Review questions

1. Describe the structure of a node in a singly linked list.

Show answer

A node has a data field that stores the item and a link (next) field that stores the location of the next node. The last node’s link is NULL.

2. Why does a linked list need a head variable? What value does it hold when the list is empty?

Show answer

head stores the location of the first node, so the list can be reached. When the list is empty, head is NULL.

3. Write pseudocode to count the nodes in a singly linked list.

Show answer

count ← 0
current ← head
WHILE current ≠ NULL DO
count ← count + 1
current ← current.next
ENDWHILE
OUTPUT count

4. Explain, in order, the two link changes needed to insert a new node after a node called prev.

Show answer

First set new.next to prev.next so the new node points to the rest of the list. Then set prev.next to new. Doing it the other way round loses the rest of the list.

5. A list is head → A → B → C → NULL. Describe how to delete B.

Show answer

Find B while remembering the node before it (A). Set A.next to B.next (C). B is no longer reachable and its node can be freed.

6. Give two advantages and one disadvantage of a linked list compared with an array.

Show answer

Advantages: insertion and deletion in the middle need no shifting; the list can grow while free nodes or memory remain. Disadvantage: no direct access by position, so reaching an item or searching means following links one by one (and each node needs extra space for its link).

7. data = {17, 42, 8, 23}, next = {3, -1, 0, 1}, head = 2. List the values in order.

Show answer

8, 17, 23, 42 (slots 2, 0, 3, 1).

8. Why can binary search not be used on a singly linked list, even if it is sorted?

Show answer

Binary search needs to jump straight to the middle item. In a linked list the only way to reach a node is to follow links from head, so there is no direct access to the middle.

Homework

  1. Draw the list and the data and next arrays (5 slots) after: insert at front 8, insert at front 3, insert in order 5, delete 3, insert in order 9.
  2. Write pseudocode for insertEnd(value) that adds a node after the last node. Remember the empty-list case.
  3. Add a function to list_array.c that prints the free list (the slots not in use).
  4. Write pseudocode for a linked stack: push and pop both work at head. Why is there no overflow until free nodes run out?
  5. Research doubly linked lists. Draw one with three nodes and explain one operation that becomes easier.

Mastery quiz: Singly linked lists

This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.

Mastery quiz: Singly Linked Lists: Diagrams, Algorithms and Array-Based Nodes in C

Your course badges: loading saved progress…

View badges

    No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.

    Saved in this browser on this device. Clearing browser data may remove your badges.

    Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.

    1. What two parts does every node in a singly linked list have?
    2. What does head = NULL mean?
    3. Which operation is associated with a linked list ADT?
    4. To insert a new node at the front, the correct order is...
    5. Deleting the first node requires changing...
    6. Searching a sorted singly linked list must be...
    7. In the array model, what does next[i] = -1 mean?
    8. data = {5, 9, 2}, next = {-1, 0, 1}, head = 2. What is the second value in the list?
    9. What is the free list used for?
    10. Main advantage of a linked list over an array for an ordered register?

    Exam tips

    Specimen Unit 2 Paper 01 (2021), Items 11 and 12. A diagram shows boxes joined by arrows ending in NULL. Recognise it as a linked list (not a stack or queue), and associate it with list operations such as insert, rather than push, pop, enqueue or dequeue.

    Diagram questions. Draw each node as a two-part box (data | next) with an arrow, label head, and end with NULL. When asked to show an insertion or deletion, draw the "before" and "after" and number the link changes in the order they happen.

    Algorithm questions. Always handle the empty list and the first-node case. Use a variable that moves along the list (current) and, for deletion, one that trails behind it (prev).

    More worked answers are on the CS Solutions page.

    Previous: Unit 2 • Module 1 • Lesson 05 – Circular Queues: Wrapping Around, Full vs Empty, in C. Next: Unit 2 • Module 1 • Lesson 07 – Searching in C: Linear Search and Binary Search.

    Syllabus link: CAPE Computer Science (CXC A19/U2/21), Data Structures (Unit 2, Module 1). Specific Objective 1: explain the concept of an abstract data type (linked lists). Specific Objective 2: distinguish among ADTs (singly linked lists: definition, structure and operation). Specific Objective 3: perform basic operations on linked lists using diagrams and algorithms.

    Video search terms

    Search YouTube for: "singly linked list explained", "linked list insert delete diagram", "linked list using arrays next pointer".

    Try it 4Quick quiz

    Tap an answer. All eight questions are self-checks on this lesson.

    Updates

    2026/12/01

    - First version of the lesson.

    © 2026 islandclass.org

    Leave a Reply