data-structures · beginner · ~15 min
Traverse a singly-linked list.
Count the nodes in a singly-linked list.
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.
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.
int: the number of nodes, counting from head until next is NULL.
1 -> 2 -> 3 -> NULL -> 3
NULL -> 0
9 -> NULL -> 1
NULL head returns 0.head: pointer to the first node_t (given: int v; node_t *next;); may be NULL.
int: number of nodes reachable from head.
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.