data-structures · beginner · ~15 min

Sum of a linked list

Accumulate while traversing a list.

Challenge

Add up the values stored in a singly-linked list.

Task

Given the node type typedef struct node { int v; struct node *next; } node_t;, implement long list_sum(node_t *head) that returns the sum of every node's v field.

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

long: the sum of all v values.

Example

1 -> 2 -> 3 -> NULL   ->   6
NULL                  ->   0

Edge cases

  • A NULL head returns 0.
  • Accumulate in a long so a long list of large values does not overflow.

Input format

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

Output format

long: sum of all node v values.

Constraints

Accumulate in long to avoid overflow.

Starter code

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

long list_sum(node_t *head) {
    /* TODO */
    return 0;
}

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