data_structures

data structures in C
Log | Files | Refs | Feed

commit f107c552c0ecf0eaca0f9b1b5d4e90b5d4097530
parent 4b7dd718a203b7f204691c628573b0b32aa5f91d
Author: Jenny Doe <tng@soykaf.me>
Date:   Thu, 21 Mar 2019 22:27:30 +0100

added: dlist_ins_prev() and tweaked dlist_remove()

Diffstat:
Mdlist.c | 48++++++++++++++++++++++++++++++++++++++++--------
Mdlist.h | 1+
Mdlist_test.c | 4++--
3 files changed, 43 insertions(+), 10 deletions(-)

diff --git a/dlist.c b/dlist.c @@ -71,25 +71,57 @@ dlist_ins_next(dList * list, dListElmt * left, void *data) } int -dlist_remove(dList * list, dListElmt * to_remove, void **data) +dlist_ins_prev(dList * list, dListElmt * right, void *data) +{ + /* silently fail */ + if (list->size == UINT_MAX - 1) { + return (1); + } + + dListElmt *new_element = malloc(sizeof(dListElmt)); + if (new_element == NULL) + return (1); + + new_element->data = data; + + if (list->size == 0) { /* insert head */ + new_element->next = NULL; + new_element->prev = NULL; + + list->head = new_element; + list->tail = new_element; + } else { /* insert after `right` */ + new_element->next = right; + new_element->prev = right->prev; + + right->prev = new_element; + + if (new_element->prev != NULL) + new_element->prev->next = new_element; + else + list->head = new_element; + } + + ++(list->size); + + return (0); +} + +int +dlist_remove(dList * list, dListElmt * old, void **data) { - dListElmt *old; if (list->size == 0) return (1); - if (list->size == 1) { + if (old == NULL) old = list->head; + if (list->size == 1) { list->head = NULL; list->tail = NULL; } else { - if (to_remove == NULL) - old = list->head; - else - old = to_remove; - if (old->next == NULL) list->tail = old->prev; else diff --git a/dlist.h b/dlist.h @@ -27,6 +27,7 @@ void dlist_destroy(dList *); /* returns 0 on success, 1 when malloc fail */ int dlist_ins_next(dList *, dListElmt *, void *); +int dlist_ins_prev(dList *, dListElmt *, void *); /* returns 0 on success, 1 if list's size is 0 */ int dlist_remove(dList *, dListElmt *, void **); diff --git a/dlist_test.c b/dlist_test.c @@ -20,7 +20,7 @@ main(void) dlist_ins_next(my_list, NULL, &t[0]); /* push 'a' */ dlist_ins_next(my_list, my_list->head, &t[0]); /* push 'a' */ - dlist_ins_next(my_list, my_list->head, &t[1]); /* push 'b' */ + dlist_ins_prev(my_list, my_list->head->next, &t[1]); /* push 'b' */ dlist_ins_next(my_list, my_list->head, &t[2]); /* push 'c' */ dlist_ins_next(my_list, my_list->tail, &u[0]); /* queue 'x' */ @@ -29,7 +29,7 @@ main(void) dlist_ins_next(my_list, my_list->tail, &u[2]); /* queue 'z' */ - void *dummy; + void *dummy; dlist_remove(my_list, my_list->head, &dummy); dlist_remove(my_list, my_list->tail, &dummy);