Ok added insert, need test for that and add type restrictions with cpp Concepts (HATE that name)
This commit is contained in:
@@ -107,6 +107,15 @@ public:
|
|||||||
*/
|
*/
|
||||||
LinkedListErr set(size_t index, const T& value);
|
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
|
* @brief Busca un valor dentro de la lista
|
||||||
*
|
*
|
||||||
@@ -192,6 +201,46 @@ LinkedListErr LinkedList<T>::set(size_t index, const T& val) {
|
|||||||
return LinkedListErr::LINKEDLIST_OK;
|
return LinkedListErr::LINKEDLIST_OK;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
LinkedListErr LinkedList<T>::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<T> *current = this->head;
|
||||||
|
for (size_t i = 1; i < index; i++) {
|
||||||
|
current = current->next;
|
||||||
|
}
|
||||||
|
|
||||||
|
Node<T> *new_node = nullptr;
|
||||||
|
|
||||||
|
try {
|
||||||
|
new_node = new Node<T>;
|
||||||
|
} 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 <typename T>
|
template <typename T>
|
||||||
LinkedListErr LinkedList<T>::append(const T& value) {
|
LinkedListErr LinkedList<T>::append(const T& value) {
|
||||||
Node<T> *new_node = nullptr;
|
Node<T> *new_node = nullptr;
|
||||||
|
|||||||
Reference in New Issue
Block a user