pvjc24/cv4/list_ops.c
2024-03-14 13:40:56 +01:00

106 lines
3.0 KiB
C

#include "list_ops.h"
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
list_t *new_list(size_t length, list_element_t elements[]) {
list_t* list = (list_t*)malloc(sizeof(list_t) + length * sizeof(list_element_t));
if (list == NULL) {
return NULL;
}
list->length = length;
memcpy(list->elements, elements, length * sizeof(list_element_t));
return list;
}
list_t *append_list(list_t *list1, list_t *list2) {
size_t total_length = list1->length + list2->length;
list_t* new_list = (list_t*)malloc(sizeof(list_t) + total_length * sizeof(list_element_t));
if (new_list == NULL) {
return NULL;
}
new_list->length = total_length;
memcpy(new_list->elements, list1->elements, list1->length * sizeof(list_element_t));
memcpy(new_list->elements + list1->length, list2->elements, list2->length * sizeof(list_element_t));
return new_list;
}
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_list = (list_t*)malloc(sizeof(list_t) + count * sizeof(list_element_t));
if (new_list == NULL) {
return NULL;
}
size_t j = 0;
for (size_t i = 0; i < list->length; ++i) {
if (filter(list->elements[i])) {
new_list->elements[j++] = list->elements[i];
}
}
new_list->length = count;
return new_list;
}
size_t length_list(list_t *list) {
return list->length;
}
list_t *map_list(list_t *list, list_element_t (*map)(list_element_t)) {
list_t* new_list = (list_t*)malloc(sizeof(list_t) + list->length * sizeof(list_element_t));
if (new_list == NULL) {
return NULL;
}
new_list->length = list->length;
for (size_t i = 0; i < list->length; ++i) {
new_list->elements[i] = map(list->elements[i]);
}
return new_list;
}
list_element_t foldl_list(list_t *list, list_element_t initial,
list_element_t (*foldl)(list_element_t, list_element_t)) {
list_element_t accumulator = initial;
for (size_t i = 0; i < list->length; ++i) {
accumulator = foldl(accumulator, list->elements[i]);
}
return accumulator;
}
list_element_t foldr_list(list_t *list, list_element_t initial,
list_element_t (*foldr)(list_element_t, list_element_t)) {
list_element_t accumulator = initial;
for (size_t i = list->length; i > 0; --i) {
accumulator = foldr(list->elements[i - 1], accumulator);
}
return accumulator;
}
list_t *reverse_list(list_t *list) {
list_t* new_list = (list_t*)malloc(sizeof(list_t) + list->length * sizeof(list_element_t));
if (new_list == NULL) {
return NULL;
}
new_list->length = list->length;
for (size_t i = 0; i < list->length; ++i) {
new_list->elements[i] = list->elements[list->length - i - 1];
}
return new_list;
}
void delete_list(list_t *list) {
free(list);
}