← Back to problems
UNSW COMP2521 · easy

Linked List: Recursive Sum

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 == NULL returning 0 (an empty list sums to 0). Using head->next == NULL drops the last node and segfaults on empty. (2) Remember to add head->value to the result of sumList(head->next).

Input

  • Line 1: integer n (may be 0).
  • Line 2: n integers.

Output

  • One line: the sum of all values (0 for an empty list).

Example: input 3 / 10 20 30 -> 60.