data-structures · beginner · ~15 min

Length of a linked list

Traverse a singly-linked list.

Challenge

Count the nodes in a singly-linked list.

Task

Given the node type typedef struct node { int v; struct node *next; } node_t;, implement int list_length(node_t *head) that returns the number of nodes in the list.

Input

head: a pointer to the first node (the type node_t is given, with an int v and a next pointer). May be NULL for an empty list.

Output

int: the number of nodes, counting from head until next is NULL.

Example

1 -> 2 -> 3 -> NULL   ->   3
NULL                  ->   0
9 -> NULL             ->   1

Edge cases

  • A NULL head returns 0.
  • A single node returns 1.

Input format

head: pointer to the first node_t (given: int v; node_t *next;); may be NULL.

Output format

int: number of nodes reachable from head.

Starter code

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

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

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