/* User-space teaching example; single-threaded, acyclic list. */
#include <stdio.h>
#include <stdlib.h>

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

static struct node *make_node(int value)
{
    struct node *p = malloc(sizeof *p);
    if (p == NULL)
        return NULL;
    p->value = value;
    p->next = NULL;
    return p;
}

/* Borrow only. Values in this example keep total within int range. */
static int sum(const struct node *p)
{
    int total = 0;
    for (; p != NULL; p = p->next)
        total += p->value;
    return total;
}

/* head addresses a valid pointer variable; the chain is owned and acyclic. */
static void destroy(struct node **head)
{
    while (*head != NULL) {
        struct node *old = *head;
        *head = old->next;
        free(old);
    }
}

int main(void)
{
    struct node *head = make_node(10);
    if (head == NULL) {
        fputs("first allocation failed\n", stderr);
        return EXIT_FAILURE;
    }
    head->next = make_node(20);
    if (head->next == NULL) {
        fputs("second allocation failed\n", stderr);
        destroy(&head);
        return EXIT_FAILURE;
    }
    printf("sum=%d\n", sum(head));
    destroy(&head);
    printf("empty=%s\n", head == NULL ? "yes" : "no");
    return EXIT_SUCCESS;
}
