data-structures · beginner · ~15 min

Linked list length

Walk a linked list using a pointer that advances along `->next`.

Challenge

Count the nodes in a singly linked list by walking it from head to tail.

The grader supplies this node type:

typedef struct node { int data; struct node *next; } node_t;

Task

Implement int list_length(const node_t *head) returning the number of nodes in the list. No main — the grader calls it.

Input

head: a pointer to the first node, or NULL for an empty list. The list is properly NULL-terminated.

Output

The node count as an int (0 for an empty list).

Example

list_length(NULL)        ->   0
list_length(1)           ->   1        (a single node)
list_length(1->2->3)     ->   3

Edge cases

  • head == NULL returns 0.

Input format

head: pointer to the first node, or NULL for an empty list.

Output format

The number of nodes as an int (0 for NULL).

Starter code

int list_length(const node_t *head) {
    /* TODO */
    return 0;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.