From 2c2bdb8b66e386e14b5cc1a35abfbf242dcf2018 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hugo=20H=C3=B6rnquist?= Date: Mon, 4 Feb 2019 00:36:57 +0100 Subject: Work on propper memmory management for linked lists. --- linked_list.inc.h | 72 ++++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 55 insertions(+), 17 deletions(-) (limited to 'linked_list.inc.h') diff --git a/linked_list.inc.h b/linked_list.inc.h index 260eaf0d..a878d075 100644 --- a/linked_list.inc.h +++ b/linked_list.inc.h @@ -4,21 +4,29 @@ int CONSTRUCTOR_DECL ( LLIST(TYPE) ) { this->length = 0; - this->head = NULL; - this->tail = NULL; - this->cur = NULL; + NEW(LINK(TYPE), head); + NEW(LINK(TYPE), tail); + this->head = head; + this->tail = tail; + head->after = tail; + tail->before = head; + this->cur = head; return 0; } -int LLIST_FREE(TYPE) (LLIST(TYPE)* this ) { +int FREE_DECL( LLIST(TYPE) ) { LINK(TYPE) *node, *next; - node = this->head; - while (node != NULL) { + node = this->head->after; + while (node->after != NULL) { next = node->after; - FFREE(TYPE, node->value); - free(node); + if (node->value != NULL) { + FFREE(TYPE, node->value); + } + // free(node); node = next; } + free (this->head); + free (this->tail); this->length = 0; return 0; } @@ -30,25 +38,32 @@ int CONSTRUCTOR_DECL ( LINK(TYPE) ) { return 0; } +int CONSTRUCTOR_DECL ( LINK(TYPE), TYPE* val ) { + this->before = NULL; + this->after = NULL; + this->value = val; + return 0; +} + int LLIST_CONS(TYPE) ( LLIST(TYPE)* lst, TYPE* val) { - NEW(LINK(TYPE), l); - l->after = lst->head; - if (l->after != NULL) { - l->after->before = l; - } - lst->head = l; - l->value = val; + NEW(LINK(TYPE), l, val); + + l->after = lst->head->after; + lst->head->after = l; + l->after->before = l; + l->before = lst->head; ++lst->length; + // TODO do I want to change that? lst->cur = l; return 0; } int DEEP_COPY(LLIST(TYPE)) ( LLIST(TYPE)* dest, LLIST(TYPE)* src ) { - LINK(TYPE)* n = src->head; + LINK(TYPE)* n = src->head->after; - while (n != NULL) { + while (n->after != NULL) { NEW(TYPE, cpy); DEEP_COPY(TYPE)(cpy, n->value); LLIST_CONS(TYPE) ( dest, cpy ); @@ -58,4 +73,27 @@ int DEEP_COPY(LLIST(TYPE)) ( LLIST(TYPE)* dest, LLIST(TYPE)* src ) { return 0; } +/* + * TODO + * this or cons links wrong, creating infinite loops. + */ +int APPEND(LLIST(TYPE)) ( LLIST(TYPE)* dest, LLIST(TYPE)* new ) { + + dest->tail->before->after = new->head->after; + new->head->after->before = dest->tail->before; + LINK(TYPE)* old_tail = dest->tail; + dest->tail = new->tail; + dest->length += new->length; + + // free(old_tail); + // free(new->head); + + /* + * TODO `new` can now be handled as an empty husk. + * Somehow it needs to be collected + */ + + return 0; +} + #endif /* TYPE */ -- cgit v1.2.3