From 28d2e7604dee05daca4a000b67bfd1f92985c4be Mon Sep 17 00:00:00 2001 From: ov075wu Date: Thu, 17 Apr 2025 13:21:48 +0200 Subject: [PATCH] refresh --- du6/list_ops.c | 87 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) diff --git a/du6/list_ops.c b/du6/list_ops.c index 7310c92..7979cc1 100644 --- a/du6/list_ops.c +++ b/du6/list_ops.c @@ -2,3 +2,90 @@ #include #include "list_ops.h" +list_t *new_list(size_t length, list_element_t elements[]) { + list_t *list = malloc(sizeof(list_t) + length * sizeof(list_element_t)); + if (!list) { + return NULL; + } + list->length = length; + + for (size_t i = 0; i < length; i++) { + list->elements[i] = elements[i]; + } + + return list; +} + +list_t *new_list(size_t length, list_element_t elements[]) { + list_t *result = malloc(sizeof(list_t) + sizeof(list_element_t) * length); + if (result == NULL) { + return NULL; + } + result->length = length; + + if (elements != NULL) { + for (size_t idx = 0; idx < length; ++idx) { + result->elements[idx] = elements[idx]; + } + } + + return result; +} + +void delete_list(list_t *lst) { + if (lst != NULL) { + free(lst); + } +} + +size_t length_list(list_t *lst) { + return (lst == NULL) ? 0 : lst->length; +} + +list_t *append_list(list_t *first, list_t *second) { + size_t a = first ? first->length : 0; + size_t b = second ? second->length : 0; + + size_t total = a + b; + list_t *joined = malloc(sizeof(list_t) + total * sizeof(list_element_t)); + if (!joined) { + return NULL; + } + joined->length = total; + + for (size_t i = 0; i < a; i++) { + joined->elements[i] = first->elements[i]; + } + + for (size_t j = 0; j < b; j++) { + joined->elements[a + j] = second->elements[j]; + } + + return joined; +} + +list_t *filter_list(list_t *list, bool (*filter)(list_element_t)) { + size_t count = 0; + for (size_t i = 0; i < list->length; i++) { + if (filter(list->elements[i])) { + count++; + } + } + + list_t *new = malloc(sizeof(list_t) + count * sizeof(list_element_t)); + if (!new) { + return NULL; + } + new->length = count; + + size_t j = 0; + for (size_t i = 0; i < list->length; i++) { + if (filter(list->elements[i])) { + new->elements[j++] = list->elements[i]; + } + } + + return new; +} + +