Newer
Older
tree-os / src / kernel / util / list.c
#include <alloc.h>
#include <list.h>

void listAdd(ListElement **list, void *data) {
    ListElement *element = *list;
    if (element == NULL) {
        *list = malloc(sizeof(ListElement));
        element = *list;
    } else {
        for (; element->next; element = element->next) {
        }
        element->next = malloc(sizeof(ListElement));
        element = element->next;
    }
    element->next = NULL;
    element->data = data;
}

void listAddSet(ListElement **list, void *data) {
    ListElement *element = *list;
    if (element == NULL) {
        *list = malloc(sizeof(ListElement));
        element = *list;
    } else {
        for (; element->next; element = element->next) {
            if (element->data == data) {
                return;
            }
        }
        element->next = malloc(sizeof(ListElement));
        element = element->next;
    }
    element->next = NULL;
    element->data = data;
}

uint32_t listCount(ListElement *list) {
    int count = 0;
    for (ListElement *current = list; current; current = current->next) {
        count++;
    }
    return count;
}

void *popBeginning(ListElement **list) {
    if (*list == NULL) {
        return NULL;
    }
    ListElement *element = *list;
    void *result = (*list)->data;
    *list = (*list)->next;
    free(element);
    return result;
}

void *popEnd(ListElement **list) {
    if (list == NULL) {
        return NULL;
    }
    ListElement *before = NULL;
    ListElement *current = *list;
    for (; current->next; current = current->next) {
        before = current;
    }
    void *result = current->data;
    free(current);
    if (before != NULL) {
        before->next = NULL;
    } else {
        *list = NULL;
    }
    return result;
}