From a514490dcbb4aaaca3a5e4fc71ef194fea18b37f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hugo=20H=C3=B6rnquist?= Date: Tue, 5 Feb 2019 23:17:08 +0100 Subject: Add llist FIRST & LAST, rewrote code to use them. --- linked_list.h | 3 +++ linked_list.inc.h | 31 ++++++++++++++++++------------- scheme.scm.c | 2 +- 3 files changed, 22 insertions(+), 14 deletions(-) diff --git a/linked_list.h b/linked_list.h index 5bf3db15..515fa4af 100644 --- a/linked_list.h +++ b/linked_list.h @@ -22,6 +22,9 @@ typedef struct { int length; } LLIST(TYPE); +#define FIRST(lst) (lst)->head->after +#define LAST(lst) (lst)->tail->before + INIT_F ( LLIST(TYPE) ); FREE_F ( LLIST(TYPE) ); diff --git a/linked_list.inc.h b/linked_list.inc.h index 2622eb4b..1522a685 100644 --- a/linked_list.inc.h +++ b/linked_list.inc.h @@ -56,10 +56,12 @@ INIT_F ( LINK(TYPE), TYPE* val ) { int PUSH(LLIST(TYPE)) ( LLIST(TYPE)* lst, TYPE* val) { NEW(LINK(TYPE), link, val); - link->after = lst->head->after; - lst->head->after = link; + link->after = FIRST(lst); + FIRST(lst) = link; + link->after->before = link; - link->before = lst->head; + link->before = lst->head; + ++lst->length; // TODO do I want to change that? @@ -69,7 +71,7 @@ int PUSH(LLIST(TYPE)) ( LLIST(TYPE)* lst, TYPE* val) { } int DEEP_COPY(LLIST(TYPE)) ( LLIST(TYPE)* dest, LLIST(TYPE)* src ) { - LINK(TYPE)* n = src->head->after; + LINK(TYPE)* n = FIRST(src); while (n->after != NULL) { NEW(TYPE, cpy); @@ -89,22 +91,25 @@ int DEEP_COPY(LLIST(TYPE)) ( LLIST(TYPE)* dest, LLIST(TYPE)* src ) { */ int APPEND(LLIST(TYPE)) ( LLIST(TYPE)* dest, LLIST(TYPE)* new ) { - LINK(TYPE)* og_new_head = new->head; - dest->tail->before->after = new->head->after; - new->head->after->before = dest->tail->before; - LINK(TYPE)* old_tail = dest->tail; + /* Link end of dest onto start of new. */ + LAST(dest)->after = FIRST(new); + FIRST(new)->before = LAST(dest); + + /* Free the two now not needed end links. */ + free(new->head); + free(dest->tail); + + /* Update dest with new tail ptr. */ dest->tail = new->tail; - dest->length += new->length; - free(old_tail); - free(og_new_head); + dest->length += new->length; return 0; } int SIZE(LLIST(TYPE)) ( LLIST(TYPE)* llist ) { int size = 0; - LINK(TYPE)* l = llist->head->after; + LINK(TYPE)* l = FIRST(llist); while (l->after != NULL) { ++size; } @@ -112,7 +117,7 @@ int SIZE(LLIST(TYPE)) ( LLIST(TYPE)* llist ) { } int EMPTY(LLIST(TYPE)) ( LLIST(TYPE)* llist ) { - return llist->head->after == llist->tail; + return FIRST(llist) == llist->tail; } #endif /* TYPE */ diff --git a/scheme.scm.c b/scheme.scm.c index da8cd3f1..a7ddc27d 100644 --- a/scheme.scm.c +++ b/scheme.scm.c @@ -53,7 +53,7 @@ SCM_DEFINE (calendar_get_attr, "calendar-get-attr", 3, 0, 0, // TODO actuall iterators // TODO this reverses the list - for ( LINK(strbuf)* n = c->vals.head->after; + for ( LINK(strbuf)* n = FIRST(&c->vals); n->after != NULL; n = n->after) { llist = scm_cons(scm_from_strbuf(n->value), llist); -- cgit v1.2.3