Added linkedlist_delete, funtions by index, one test was added and passed for checking when eliminate head, subsequent commits will add more tests for this function

This commit is contained in:
2026-02-12 13:08:05 -06:00
parent 7611096e13
commit 643fcf9cb6
3 changed files with 66 additions and 2 deletions

View File

@@ -22,5 +22,6 @@ LinkedListErr linkedlist_delete(LinkedList *ll, size_t index);
LinkedListErr linkedlist_pop(LinkedList *ll, size_t index, void *out);
LinkedListErr linkedlist_insert(LinkedList *ll, size_t index, void *out);
LinkedListErr linkedlist_get(const LinkedList *ll, size_t index, void *out);
LinkedListErr linkedlist_len(const LinkedList *ll, size_t *out);
#endif /* ifndef LINKEDLIST_H */

View File

@@ -120,3 +120,45 @@ LinkedListErr linkedlist_get(const LinkedList *ll, size_t index, void *out) {
return LLIST_OK;
}
LinkedListErr linkedlist_delete(LinkedList *ll, size_t index) {
if (ll == NULL) {
return LLIST_NULL;
}
if (index >= ll->len) {
return LLIST_OUT_OF_BOUNDS;
}
Node *before = NULL;
Node *current = ll->head;
for (size_t i = 0; i < index; i++) {
before = current;
current = current->next;
}
// Take the node OUT of the list, if before is NULL that means
// is the head we are talking about so the change is different
if (before == NULL) {
ll->head = current->next;
} else {
// If its last current-next is just NULL so is okay
before->next = current->next;
}
// Fuck them dangling pointers
free(current->data);
free(current);
ll->len = ll->len - 1;
return LLIST_OK;
}
LinkedListErr linkedlist_len(const LinkedList *ll, size_t *out) {
if (ll == NULL) {
return LLIST_NULL;
}
*out = ll->len;
return LLIST_OK;
}

View File

@@ -7,7 +7,7 @@
#include <setjmp.h>
#include <cmocka.h>
static void linkedlist_test_append(void **state) {
static void linkedlist_test_append_3_int(void **state) {
(void) state;
LinkedList *ll;
@@ -23,9 +23,30 @@ static void linkedlist_test_append(void **state) {
linkedlist_destroy(ll);
}
static void linkedlist_test_delete_head(void **state) {
(void) state;
LinkedList *ll;
linkedlist_create(&ll, sizeof(int));
for (int i = 0; i < 3; i++) {
linkedlist_append(ll, &i);
}
linkedlist_delete(ll, 0);
size_t len;
linkedlist_len(ll,&len);
assert_int_equal(len, 2);
for (int i = 0; i < 2; i++) {
int n;
linkedlist_get(ll, i, &n);
assert_int_equal(n, i + 1);
}
linkedlist_destroy(ll);
}
int main(void) {
const struct CMUnitTest tests[] = {
cmocka_unit_test(linkedlist_test_append),
cmocka_unit_test(linkedlist_test_append_3_int),
cmocka_unit_test(linkedlist_test_delete_head),
};
return cmocka_run_group_tests(tests, NULL, NULL);