From 0e246be627c33f33d82a0fb2e5b43dd3fa024e0c Mon Sep 17 00:00:00 2001 From: ENGO150 Date: Thu, 21 Nov 2024 16:49:27 +0100 Subject: [PATCH] created why2_list_push_at fn in llist pushes to specific position --- include/llist.h | 1 + src/core/lib/utils/llist.c | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/include/llist.h b/include/llist.h index 20fbe60..ec7dea1 100644 --- a/include/llist.h +++ b/include/llist.h @@ -40,6 +40,7 @@ typedef struct //FUNCTIONS void why2_list_push(why2_list_t *list, void *value, unsigned long size); //PUSH ELEMENT TO LIST BACK +void why2_list_push_at(why2_list_t *list, unsigned long index, void *value, unsigned long size); //PUSH ELEMENT TO INDEX index of LIST void why2_list_remove(why2_list_t *list, why2_node_t *node); //REMOVE ELEMENT void why2_list_remove_back(why2_list_t *list); //REMOVE LAST ELEMENT why2_node_t *why2_list_find(why2_list_t *list, void *value); //FIND ELEMENT IN LIST diff --git a/src/core/lib/utils/llist.c b/src/core/lib/utils/llist.c index 82a2120..f834b21 100644 --- a/src/core/lib/utils/llist.c +++ b/src/core/lib/utils/llist.c @@ -51,6 +51,31 @@ void why2_list_push(why2_list_t *list, void *value, unsigned long size) list -> head = buffer; } +void why2_list_push_at(why2_list_t *list, unsigned long index, void *value, unsigned long size) +{ + //CREATE NODE + why2_node_t *head = list -> head; + why2_node_t *new_node = malloc(sizeof(why2_node_t)); + new_node -> value = malloc(size); + + //INSERT DATA + memcpy(new_node -> value, value, size); + + if (index != 0 && head != NULL) //ISN'T FIRST + { + why2_node_t *node_before = head; + for (unsigned long j = 0; j < index - 1 && j < why2_list_get_size(list); j++) node_before = node_before -> next; //SCROLL TO THE POSITION + + new_node -> next = node_before -> next; //SEW THE LIST BACK + node_before -> next = new_node; + } else //ADD BEFORE THE WHOLE LIST + { + new_node -> next = head; + + list -> head = new_node; + } +} + void why2_list_remove(why2_list_t *list, why2_node_t *node) { if (node == NULL) return; //NULL NODE