#include <stdio.h>
#include <stdlib.h>

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

void list_add(struct list **li, int value);
struct list *list_fromarray(int *v, int n);
void list_print(struct list *li, const char *msg);
void list_free(struct list *li);

int main(void) {
    struct list *list;
    int test[] = {1, 4, 8, 9, 13, 42};
    list = list_fromarray(test, sizeof test/sizeof *test);
    list_print(list, "final list");
    list_free(list);
}

struct list *list_fromarray(int *v, int n) {
    struct list *li = NULL;
    for (int k = n - 1; k >= 0; k--) {
        list_add(&li, v[k]);
    }
    return li;
}

void list_add(struct list **li, int value) {
    struct list *node;
    node = malloc(sizeof *node);
    node->value = value;
    node->next = *li;
    *li = node;
}

void list_print(struct list *li, const char *msg) {
    printf("%s:", msg);
    while (li) {
        printf(" %d", li->value);
        li = li->next;
    }
    puts("");
}

void list_free(struct list *li) {
    while (li) {
        struct list *bak = li;
        li = li->next;
        free(bak);
    }
}
