From 06091a1b7d3555c20cc7ddc3e61e39f0103a5759 Mon Sep 17 00:00:00 2001 From: LaEntropiaa Date: Sat, 21 Mar 2026 23:25:57 -0600 Subject: [PATCH] Ok, corrected insert, should have copied directly from my c implementation, all tests good, just need to test insert middle --- include/linkedlist.h | 17 +++++++++-------- test/test_linkedlist.cpp | 22 ++++++++++++++++++++++ 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/include/linkedlist.h b/include/linkedlist.h index 25ac62c..ce7fa29 100644 --- a/include/linkedlist.h +++ b/include/linkedlist.h @@ -235,37 +235,38 @@ LinkedListErr LinkedList::insert(size_t index, const T& value) { return this->append(value); } - if (index >= this->size) { + if (index > this->size) { return LinkedListErr::LINKEDLIST_OUT_OF_BOUNDS; } - // If index is head if (index == 0) { return this->prepend(value); } - // If index is tail - if (index == this->size - 1) { + if (index == this->size) { return this->append(value); } - Node *current = this->head; + Node* current = this->head; + for (size_t i = 1; i < index; i++) { current = current->next; } - Node *new_node = nullptr; + Node* new_node = nullptr; try { new_node = new Node; - } catch(const std::bad_alloc&) { + } catch (const std::bad_alloc&) { return LinkedListErr::LINKEDLIST_BAD_ALLOC; } new_node->data = value; - new_node->next = current->next->next; + new_node->next = current->next; current->next = new_node; + this->size++; + return LinkedListErr::LINKEDLIST_OK; } diff --git a/test/test_linkedlist.cpp b/test/test_linkedlist.cpp index 881c527..091337c 100644 --- a/test/test_linkedlist.cpp +++ b/test/test_linkedlist.cpp @@ -279,3 +279,25 @@ TEST_CASE("Insert at start of list", "[linkedlist]") { REQUIRE(list.len() == 4); REQUIRE(list.get(0) == 90); } + +TEST_CASE("Insert at end of list", "[linkedlist]") { + LinkedList list = {}; + + REQUIRE(list.len() == 0); + + list.append(8); + REQUIRE(list.len() == 1); + REQUIRE(list.get(0) == 8); + + list.append(9); + REQUIRE(list.len() == 2); + REQUIRE(list.get(1) == 9); + + list.append(10); + REQUIRE(list.len() == 3); + REQUIRE(list.get(2) == 10); + + list.insert(2, 90); + REQUIRE(list.len() == 4); + REQUIRE(list.get(2) == 90); +}