Source

randomc / list.c

Full commit
#include <stdlib.h>

#include "list.h"

struct list* list_init(void *data) {
    struct list *l = NULL;

    l = malloc(sizeof(struct list));
    if (l == NULL)
        return NULL;

    l->prev = l->next = NULL;
    l->data = data;

    return l;
}

struct list* list_append(struct list *l, void *data) {
    struct list *next = NULL, *last = NULL;

    if (l == NULL)
        return NULL;

    next = list_init(data);
    if (next == NULL)
        return NULL;

    last = list_tail(l);
    last->next = next;
    next->prev = last;

    return next;
}

struct list* list_head(struct list *l) {
    if (l == NULL)
        return NULL;

    while (l->prev != NULL) {
        l = l->prev;
    }

    return l;
}

struct list* list_tail(struct list *l) {
    if (l == NULL)
        return NULL;

    while (l->next != NULL) {
        l = l->next;
    }

    return l;
}

size_t list_len(struct list *l) {
    size_t len = 0;
    for (; l != NULL; l = l->next) {
        len += 1;
    }
    return len;
}

void list_free(struct list *l) {
    struct list *next = l;

    while (next != NULL) {
        l = next;
        next = next->next;
        free(l);
    }
}