feat(linked list): implemented insert at index

This commit is contained in:
Mineplay 2025-04-25 17:04:33 -05:00
parent fee99c8cdd
commit 8370ada3c4
3 changed files with 40 additions and 0 deletions

View file

@ -44,6 +44,8 @@ FledastyError fledasty_linked_list_destroy(FledastyLinkedList *current_linked_li
FledastyError fledasty_linked_list_append(FledastyLinkedList *current_linked_list, void *value);
FledastyError fledasty_linked_list_insert_at_index(FledastyLinkedList *current_linked_list, const size_t index, void *value);
static inline bool fledasty_linked_list_is_empty(FledastyLinkedList *current_linked_list) { return current_linked_list->size == 0; }
#endif

View file

@ -22,6 +22,7 @@
* -----------------------------------------------------------------------------
*/
#include "../../Include/Fledasty/Core/LinkedList.h"
#include "Fledasty/Utils/Error.h"
#include <Hallocy/Core/Allocator.h>
#include <Hallocy/Core/Memory.h>
@ -104,3 +105,37 @@ FledastyError fledasty_linked_list_append(FledastyLinkedList *current_linked_lis
return FLEDASTY_ERROR_NONE;
}
FledastyError fledasty_linked_list_insert_at_index(FledastyLinkedList *current_linked_list, const size_t index, void *value) {
if (current_linked_list == NULL || value == NULL) {
return FLEDASTY_ERROR_INVALID_POINTER;
}
if (index > current_linked_list->size) {
return FLEDASTY_ERROR_INDEX_OUT_OF_RANGE;
}
FledastyLinkedListNode *new_node = (FledastyLinkedListNode*)hallocy_malloc(sizeof(FledastyLinkedListNode));
new_node->value = hallocy_malloc(current_linked_list->element_byte_size);
hallocy_copy_memory(new_node->value, value, current_linked_list->element_byte_size);
if (index == 0) {
new_node->next = current_linked_list->start;
current_linked_list->start = new_node;
} else if (index == current_linked_list->size) {
current_linked_list->end->next = new_node;
current_linked_list->end = new_node;
} else {
FledastyLinkedListNode *current_node = current_linked_list->start;
for (size_t node = 0; node < index - 1; node += 1) {
current_node = current_node->next;
}
new_node->next = current_node->next;
current_node->next = new_node;
}
current_linked_list->size += 1;
return FLEDASTY_ERROR_NONE;
}

View file

@ -110,6 +110,9 @@ int main() {
fledasty_linked_list_append(&test_linked_list, &i);
}
insert_value = 35;
fledasty_linked_list_insert_at_index(&test_linked_list, 1, &insert_value);
FledastyLinkedListNode *test_linked_list_node = test_linked_list.start;
for (int i = 0; i < test_linked_list.size; i += 1) {
printf("Linked list get: %d\n", *(int*)test_linked_list_node->value);