From 7c62454f092ecedebd9e245dc0c9df276b288ada Mon Sep 17 00:00:00 2001 From: Thomas Schmucker Date: Thu, 3 Sep 2020 09:42:39 +0200 Subject: erste Version einer einfach verketteten Liste mit tail-Wächter MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- list-tail-node.c | 129 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 129 insertions(+) create mode 100644 list-tail-node.c (limited to 'list-tail-node.c') diff --git a/list-tail-node.c b/list-tail-node.c new file mode 100644 index 0000000..d187241 --- /dev/null +++ b/list-tail-node.c @@ -0,0 +1,129 @@ +/* Standard C */ +#include +#include +#include + +/* Project */ +#include "util.h" + +typedef int T; + +struct list_node { + struct list_node *next; + T data; +}; + +struct list { + struct list_node *head, *tail; +}; + +void +list_init(struct list *list) +{ + list->head = NULL; +} + +static struct list_node * +create_node(struct list_node *next, T data) +{ + struct list_node *node = malloc(sizeof *node); + + if ( node != NULL ) { + node->next = next; + node->data = data; + } + return node; +} + +void +list_push_back(struct list *list, T data) +{ + struct list_node *node = create_node(NULL, data); + + if ( node != NULL ) { + if ( list->head == NULL ) { + list->head = node; + } + else { + list->tail->next = node; + } + list->tail = node; + } + else { + ERROR("out of memory"); + } +} + +void +list_push_front(struct list *list, T data) +{ + struct list_node *node = create_node(list->head, data); + + if ( node != NULL ) { + if ( list->head == NULL ) { // Einfügen in eine leere Liste? + list->tail = node; + } + list->head = node; + } + else { + ERROR("out of memory"); + } +} + +bool +list_pop_front(struct list *list, T *data) +{ + if ( list->head != NULL ) { + struct list_node *next = list->head->next; + *data = list->head->data; + free(list->head); + list->head = next; + + return true; + } + else + return false; +} + +bool +list_empty(struct list *list) +{ + return list->head == NULL; +} + +void +list_free(struct list *list) +{ + struct list_node *item, *next; + + for ( item = list->head; item; item = next ) { + next = item->next; + free(item); + } +} + +int +main() +{ + struct list list[1]; + + list_init(list); + + for ( int i = 0; i != 10; ++i ) + list_push_front(list, -i); + + for ( int i = 0; i != 10; ++i ) + list_push_back(list, i); + + while ( !list_empty(list) ) { + int i; + if ( list_pop_front(list, &i) ) + printf("%d\n", i); + else + ERROR("this shouldn't happen!"); + } + + list_free(list); + + return EXIT_SUCCESS; +} -- cgit v1.3