From 8db61cec448aac5ff5ec1684bb51559d39c083dd Mon Sep 17 00:00:00 2001 From: simon Date: Wed, 11 Dec 2024 03:10:11 +0100 Subject: [PATCH] new file: src/llist.c new file: src/llist.h --- src/llist.c | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++ src/llist.h | 23 +++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100644 src/llist.c create mode 100644 src/llist.h diff --git a/src/llist.c b/src/llist.c new file mode 100644 index 0000000..4b8565f --- /dev/null +++ b/src/llist.c @@ -0,0 +1,63 @@ +#include "llist.h" +#include + +/* create new linked list + * use llistFree after use + * retturns NULL on failure + */ +llist *llistNew(void *data, int (*cmpFN)(void *a, void *b)) { + llist *r = (llist *)malloc(sizeof(llist)); + if (r != NULL) { + r->cmpFn = cmpFN; + r->data = data; + r->prev = NULL; + r->next = NULL; + } + return r; +} + +/*return last node of linked list; + */ +llist *llistTail(llist *l) { + llist *tail = l; + while (tail->next != NULL) { + tail = tail->next; + } + return tail; +} + +/* creates new node from data and appends it to head + * + */ +llist *llistAppend(llist *head, void *data) { + llist *new = llistNew(data, head->cmpFn); + if (new != NULL) { + llist *tail = llistTail(head); + new->data = data; + new->next = NULL; + new->prev = tail; + tail->next = new; + } + return new; +} + +void *llistGet(llist *head, void *key) { + llist *c = head; + while (c != NULL) { + if (key == c) { + return c; + } + c = c->next; + } + return NULL; +} +bool llistContains(llist *head, void *key) { + return llistGet(head, key) != NULL; +} +void llistFree(llist *head) { + while (head != NULL) { + llist *tmp = head->next; + free(head); + head = tmp; + } +} diff --git a/src/llist.h b/src/llist.h new file mode 100644 index 0000000..679b33a --- /dev/null +++ b/src/llist.h @@ -0,0 +1,23 @@ +#ifndef LLIST +#define LLIST +#include + +typedef struct llist { + void *data; + struct llist *next; + struct llist *prev; + int (*cmpFn)(void *a, void *b); // function that compares data +} llist; + +// create new linked list with content(void* data) and cmpFN +llist *llistNew(void *data, int (*cmpFN)(void *a, void *b)); +// create new node with data and append to tail of head +llist *llistAppend(llist *head, void *data); +// return llistNode that contains key or NULL +void *llistGet(llist *head, void *key); +// TURE if llist contains key +bool llistContains(llist *head, void *key); +// free llist node (Does Not free data it contains!!) +void llistFree(llist *head); + +#endif