/* 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; if ( data != NULL ) { *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; }