// // Created by william on 1/16/24. // #include #include #include #include #include "linked_list.h" LinkedList linked_list_init() { LinkedList list; list.head = NULL; list.end = NULL; return list; } void linked_list_add(LinkedList *list, void *data) { LinkedListNode *node = malloc(sizeof(LinkedListNode)); if (node == NULL) { perror("Failed to allocate memory for linked list node"); exit(EXIT_FAILURE); } node->data = data; node->previous = list->end; node->next = NULL; if (list->head == NULL) { list->head = node; } if (list->end != NULL) { list->end->next = node; } list->end = node; } LinkedListNode *linked_list_get_if(LinkedList *list, bool(*predicate)(void *, void *), void *userdata) { LinkedListNode *node = list->head; while (node != NULL) { if (predicate(node->data, userdata)) { return node; } node = node->next; } return NULL; } LinkedListNode *linked_list_get_near(LinkedList *list, int(*predicate)(void *, void *), void *userdata) { LinkedListNode *near_node = list->head; int current_distance = predicate(near_node->data, userdata); if (current_distance == 0) { return near_node; } // TODO int last_distance = 0x7fffffff; LinkedListNode *node = near_node->next; while (current_distance < last_distance && near_node->next != NULL) { node = near_node->next; last_distance = current_distance; current_distance = predicate(node->data, userdata); } // After the loop, we have found the nearest node in the list, assuming there is only one point of convergence return near_node; } void linked_list_uninit(LinkedList *list) { assert(list != NULL); LinkedListNode *node = list->head; while (node != NULL) { LinkedListNode *current_node = node; node = node->next; free(current_node->data); free(current_node); } }