Untitled

mail@pastecode.io avatar
unknown
c_cpp
2 years ago
2.2 kB
4
Indexable
// PUBLIC DOMAIN & CC0 LICENSE - 2023 May 1 jon@rm-f.net
#include <stdlib.h>
#include <stdio.h>

struct item {
    struct item *next;
    int data;
};

struct item *head;

struct item *item_new(int data)
{
    struct item *it = malloc(sizeof(*it));
    if (!it) { return NULL; }
    *it = (struct item){NULL, data};
    return it;
}

// insert item into head
void item_insert(struct item *it)
{
    it->next = head;
    head = it;
}

// find first match
struct item *item_find(int data)
{
    struct item *it;
    for (it = head; it; it = it->next) {
        if (it->data == data) {
            return it;
        }
    }
    return NULL;
}

// remove an item from the list
void item_remove(struct item *it)
{
    struct item *curr, **prev; /* current and previous pointer */
    // search for element matching our item, overwrite the pointer that refers to current.
    for (prev = &head, curr = head; curr; prev = &curr->next, curr = curr->next) {
        if (curr == it) {
            *prev = it->next;
            it->next = NULL;
            return;
        }
    }
}

// quickly remove first item from list
struct item *item_pop(void)
{
        struct item *it = head;
        if (head) {
                head = head->next;
        }
        return it;
}

void item_dump(void)
{
    struct item *it;
    for (it = head; it; it = it->next) {
        fprintf(stdout, "[%d] -> ", it->data);
    }
    fprintf(stdout, "NULL\n");
}

int main()
{
    // Show items beinded in stack order (last in / first out)
    struct item *a = item_new(123);
    item_insert(a);
    struct item *b = item_new(456);
    item_insert(b);
    struct item *c = item_new(789);
    item_insert(c);

    fprintf(stdout, "Starting list: ");
    item_dump(); // show our complete list

    /* remove an item in the middle */
    item_remove(b);
    free(b);
    fprintf(stdout, "Removed an item: ");
    item_dump();

    /* pop the rest of the list */
    struct item *it;
    while ((it = item_pop())) {
            fprintf(stdout, "Popped [%d]\n", it->data);
            free(it);
    }

    return 0;
}