From 1d6d32d044e67fc984e5c1b8361460844fec52db Mon Sep 17 00:00:00 2001 From: mrb0nk500 Date: Wed, 27 Jul 2022 08:40:12 -0300 Subject: linked_list: Add `cleanup_linked_list()` This function cleans up a linked list by removing every node in the list. --- linked_list.c | 32 +++++++++++++++++++++----------- linked_list.h | 5 +++-- 2 files changed, 24 insertions(+), 13 deletions(-) diff --git a/linked_list.c b/linked_list.c index 792da4d..3c694be 100644 --- a/linked_list.c +++ b/linked_list.c @@ -1,6 +1,18 @@ #include #include "linked_list.h" +linked_list *get_head(linked_list *node) { + linked_list *head; + for (head = node; head != NULL && head->prev != NULL; head = head->prev); + return head; +} + +linked_list *get_tail(linked_list *node) { + linked_list *tail; + for (tail = node; tail != NULL && tail->next != NULL; tail = tail->next); + return tail; +} + linked_list *add_node(linked_list **tail, void *data) { if (tail == NULL) { return NULL; @@ -25,7 +37,6 @@ linked_list *add_node(linked_list **tail, void *data) { } } - void remove_node(linked_list *node) { if (node != NULL) { if (node->prev != NULL) { @@ -40,16 +51,15 @@ void remove_node(linked_list *node) { } } -linked_list *get_head(linked_list *node) { - linked_list *head; - for (head = node; head != NULL && head->prev != NULL; head = head->prev); - return head; -} - -linked_list *get_tail(linked_list *node) { - linked_list *tail; - for (tail = node; tail != NULL && tail->next != NULL; tail = tail->next); - return tail; +void cleanup_linked_list(linked_list *node) { + if (node != NULL) { + for (node = get_tail(node); node != NULL; node = node->prev) { + if (node->next != NULL) { + remove_node(node->next); + } + } + remove_node(node); + } } int linked_list_size(linked_list *tail) { diff --git a/linked_list.h b/linked_list.h index 643e4f2..d18b859 100644 --- a/linked_list.h +++ b/linked_list.h @@ -9,10 +9,11 @@ struct linked_list { void *data; /* Pointer to data. */ }; -extern linked_list *add_node(linked_list **tail, void *data); -extern void remove_node(linked_list *node); extern linked_list *get_head(linked_list *node); extern linked_list *get_tail(linked_list *node); +extern linked_list *add_node(linked_list **tail, void *data); +extern void remove_node(linked_list *node); +extern void cleanup_linked_list(linked_list *node); extern int linked_list_size(linked_list *tail); #endif -- cgit v1.2.3-13-gbd6f