C: Add up a linked list

Walk along a linked list and add up its values.

What to build

A function that follows pointers from node to node.

Requirements

  • Complete sum, using a pointer to walk along the list.
  • Do not change main, which builds the list and frees it.

Input

The first line has n. The second line has n whole numbers.

Output

One number.

Constraints

n is from 0 to 1000. When n is 0, the second line is empty.

Example

Input:

3
1 2 3

Output:

6

Why it works

Each node knows only where the next one is, so following those pointers until NULL is the only way through the list.

Examples

Example 1 · Input
3
1 2 3
Expected output
6
Example 2 · Input
0

Expected output
0

Hints

Hint 1

The list is built for you.

Hint 2

Follow next until the pointer is NULL.

Solution

Show one correct solution (try it yourself first)
#include <stdio.h>
#include <stdlib.h>

struct node {
    int value;
    struct node *next;
};

int sum(struct node *head) {
    int total = 0;
    for (struct node *p = head; p != NULL; p = p->next) {
        total += p->value;
    }
    return total;
}

int main(void) {
    int n;
    scanf("%d", &n);
    struct node *head = NULL;
    for (int i = 0; i < n; i++) {
        struct node *new_node = malloc(sizeof(struct node));
        scanf("%d", &new_node->value);
        new_node->next = head;
        head = new_node;
    }
    printf("%d\n", sum(head));
    while (head != NULL) {
        struct node *next = head->next;
        free(head);
        head = next;
    }
    return 0;
}

Lesson: Linked lists →