eimreirrew

This commit is contained in:
Michal Utľák 2024-03-10 19:21:26 +01:00
parent e1d5ba22cf
commit 9ca763cbb8

View File

@ -1,8 +1,7 @@
#include "list_ops.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
list_t *new_list(size_t length, list_element_t elements[]) {
list_t *newList = (list_t *)malloc(sizeof(list_t) + length * sizeof(list_element_t));
@ -29,7 +28,6 @@ list_t *append_list(list_t *list1, list_t *list2) {
combinedList->length = list1->length + list2->length;
memcpy(combinedList->elements, list1->elements, list1->length * sizeof(list_element_t));
memcpy(combinedList->elements + list1->length, list2->elements, list2->length * sizeof(list_element_t));
return combinedList;
@ -40,7 +38,7 @@ list_t *filter_list(list_t *list, bool (*filter)(list_element_t)) {
return NULL;
}
list_t *filteredList = (list_t *)malloc(sizeof(list_t) + list->length * sizeof(list_element_t));
list_t *filteredList = (list_t *)malloc(sizeof(list_t));
if (filteredList == NULL) {
return NULL;
}
@ -54,7 +52,11 @@ list_t *filter_list(list_t *list, bool (*filter)(list_element_t)) {
filteredList->length = count;
memcpy(filteredList->elements, list->elements, count * sizeof(list_element_t));
filteredList->elements = (list_element_t *)malloc(count * sizeof(list_element_t));
if (filteredList->elements == NULL) {
free(filteredList);
return NULL;
}
size_t filteredIndex = 0;
for (size_t i = 0; i < list->length; ++i) {
@ -73,6 +75,31 @@ size_t length_list(list_t *list) {
return list->length;
}
list_t *map_list(list_t *list, list_element_t (*map)(list_element_t)) {
if (list == NULL || map == NULL) {
return NULL;
}
list_t *mappedList = (list_t *)malloc(sizeof(list_t) + list->length * sizeof(list_element_t));
if (mappedList == NULL) {
return NULL;
}
mappedList->length = list->length;
mappedList->elements = (list_element_t *)malloc(list->length * sizeof(list_element_t));
if (mappedList->elements == NULL) {
free(mappedList);
return NULL;
}
for (size_t i = 0; i < list->length; ++i) {
mappedList->elements[i] = map(list->elements[i]);
}
return mappedList;
}
list_element_t foldl_list(list_t *list, list_element_t initial, list_element_t (*foldl)(list_element_t, list_element_t)) {
if (list == NULL) {
return initial;
@ -113,6 +140,12 @@ list_t *reverse_list(list_t *list) {
reversedList->length = list->length;
reversedList->elements = (list_element_t *)malloc(list->length * sizeof(list_element_t));
if (reversedList->elements == NULL) {
free(reversedList);
return NULL;
}
for (size_t i = 0; i < list->length; ++i) {
reversedList->elements[i] = list->elements[list->length - i - 1];
}
@ -122,6 +155,7 @@ list_t *reverse_list(list_t *list) {
void delete_list(list_t *list) {
if (list != NULL) {
free(list->elements);
free(list);
}
}