From 0f5c87065b79c49ad81659cda108bd8304e748d3 Mon Sep 17 00:00:00 2001 From: LaEntropiaa Date: Sat, 21 Mar 2026 22:42:55 -0600 Subject: [PATCH] Ok added insert, need test for that and add type restrictions with cpp Concepts (HATE that name) --- include/linkedlist.h | 49 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/include/linkedlist.h b/include/linkedlist.h index d436734..bf9f6cf 100644 --- a/include/linkedlist.h +++ b/include/linkedlist.h @@ -107,6 +107,15 @@ public: */ LinkedListErr set(size_t index, const T& value); + /** + * @brief Inserta un valor en el index dado. + * + * @param index Indice del elemento + * @param value Nuevo valor + * @return LinkedListErr Codigo de estado + */ + LinkedListErr insert (size_t index, const T& value); + /** * @brief Busca un valor dentro de la lista * @@ -192,6 +201,46 @@ LinkedListErr LinkedList::set(size_t index, const T& val) { return LinkedListErr::LINKEDLIST_OK; } +template +LinkedListErr LinkedList::insert(size_t index, const T& value) { + if (this->is_empty()) { + return this->append(value); + } + + 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) { + return this->append(value); + } + + Node *current = this->head; + for (size_t i = 1; i < index; i++) { + current = current->next; + } + + Node *new_node = nullptr; + + try { + new_node = new Node; + } catch(const std::bad_alloc&) { + return LinkedListErr::LINKEDLIST_BAD_ALLOC; + } + + new_node->data = value; + new_node->next = current->next->next; + current->next = new_node; + + return LinkedListErr::LINKEDLIST_OK; +} + template LinkedListErr LinkedList::append(const T& value) { Node *new_node = nullptr;