data-structures · beginner · ~15 min
Accumulate while traversing a list.
Add up the values stored in a singly-linked list.
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.
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.
long: the sum of all v values.
1 -> 2 -> 3 -> NULL -> 6
NULL -> 0
NULL head returns 0.long so a long list of large values does not overflow.head: pointer to the first node_t (given: int v; node_t *next;); may be NULL.
long: sum of all node v values.
Accumulate in long to avoid overflow.
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.