From 586a95dde36c1d4f1dfd2b7590db87f6d9d55d12 Mon Sep 17 00:00:00 2001 From: "@syxhe" Date: Mon, 24 Mar 2025 15:53:14 -0500 Subject: Do some more work on the linked list --- src/ll.c | 75 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 66 insertions(+), 9 deletions(-) (limited to 'src/ll.c') diff --git a/src/ll.c b/src/ll.c index ae62e89..4819226 100644 --- a/src/ll.c +++ b/src/ll.c @@ -47,17 +47,26 @@ int dllnode_free(dllnode **n) { return 0; } -void dlinkedlist_init(dlinkedlist **ll) { - (*ll) = xcalloc(1, sizeof(**ll)); +dlinkedlist * dlinkedlist_init(void) { + dlinkedlist *ll = xcalloc(1, sizeof(*ll)); - (*ll)->start = NULL; - (*ll)->end = NULL; - (*ll)->size = 0; + ll->start = NULL; + ll->end = NULL; + ll->size = 0; - return; + return ll; } -void dlinkedlist_free(dlinkedlist **ll) { +int dlinkedlist_free(dlinkedlist **ll) { + if(!ll) { + errno = EINVAL; + return -1; + } + if(!(*ll)) { + errno = EINVAL; + return -1; + } + dllnode *p = (*ll)->start, *n; while(p != NULL) { n = p->next; @@ -67,7 +76,7 @@ void dlinkedlist_free(dlinkedlist **ll) { free(*ll); (*ll) = NULL; - return; + return 0; } int dlinkedlist_firstitem(dlinkedlist * const ll, void *data, dlinkedlist_freecallback dfreecb) { @@ -210,4 +219,52 @@ int dlinkedlist_remove(dlinkedlist * const ll, size_t index) { ll->size--; return 0; -} \ No newline at end of file +} + +size_t dlinkedlist_size(const dlinkedlist * const ll) { + if(!ll) + RETURNWERR(EINVAL, -1); + + return ll->size; +} + +int dlinkedlist_isempty(const dlinkedlist * const ll) { + if(!ll) + RETURNWERR(EINVAL, -1); + + return (ll->size == 0); +} + + + + +// Sample code +#define COMPILE_SAMPLE +#ifdef COMPILE_SAMPLE + +#include +#include + +int genfree(void *data) { + free(data); + return 0; +} + +int main() { + dlinkedlist *dll = dlinkedlist_init(); + dlinkedlist_append(dll, (void*)strdup("THIS"), genfree); + dlinkedlist_append(dll, (void*)strdup("IS"), genfree); + dlinkedlist_append(dll, (void*)strdup("A"), genfree); + dlinkedlist_append(dll, (void*)strdup("STRING"), genfree); + + // This is crashing as of right now + char *retval; + for(int i = 0; i < dlinkedlist_size(dll); i++) + printf("%s ", (((retval = (char*)dlinkedlist_get(dll, i)) != NULL) ? retval : "null") ); + printf("\n"); + + dlinkedlist_free(&dll); + + return 0; +} +#endif \ No newline at end of file -- cgit v1.2.3