Lesson 3 of 14

Length

Counting Nodes

To count the nodes in a list, traverse it and increment a counter:

int list_length(struct Node *head) {
    int count = 0;
    struct Node *cur = head;
    while (cur != NULL) {
        count++;
        cur = cur->next;
    }
    return count;
}

This runs in O(n) — there is no shortcut. You must visit every node.

Unlike arrays, a linked list has no stored length. If you need the length frequently, you'd track it in a wrapper struct.

Empty List

When head is NULL, the loop body never runs and the function returns 0. Always handle the empty case.

Your Task

Implement int list_length(struct Node *head) that returns the number of nodes.

TCC compiler loading...
Loading...
Click "Run" to execute your code.