Linked List: sum all values recursively (no loops)
Read a linked list and print the sum of all node values — but you must use recursion, no loops (echoing 2521's "no loops, recursion only" exam constraint).
Complete sumList: a list = head node + the rest of the list, so sum(head) = head->value + sum(head->next).
Pitfalls: (1) the base case is
head == NULLreturning0(an empty list sums to 0). Usinghead->next == NULLdrops the last node and segfaults on empty. (2) Remember to addhead->valueto the result ofsumList(head->next).
Input
- Line 1: integer
n(may be 0). - Line 2:
nintegers.
Output
- One line: the sum of all values (
0for an empty list).
Example: input 3 / 10 20 30 -> 60.