diff --git a/include/linkedlist.h b/include/linkedlist.h index 0f3df0a..9884c74 100644 --- a/include/linkedlist.h +++ b/include/linkedlist.h @@ -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 */ diff --git a/src/linkedlist.c b/src/linkedlist.c index 82cc14d..57e9556 100644 --- a/src/linkedlist.c +++ b/src/linkedlist.c @@ -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; +} diff --git a/tests/test_linkedlist.c b/tests/test_linkedlist.c index dc429e4..e7743e0 100644 --- a/tests/test_linkedlist.c +++ b/tests/test_linkedlist.c @@ -7,7 +7,7 @@ #include #include -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);