Ok, corrected insert, should have copied directly from my c implementation, all tests good, just need to test insert middle
This commit is contained in:
@@ -235,37 +235,38 @@ LinkedListErr LinkedList<T>::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<T> *current = this->head;
|
||||
Node<T>* current = this->head;
|
||||
|
||||
for (size_t i = 1; i < index; i++) {
|
||||
current = current->next;
|
||||
}
|
||||
|
||||
Node<T> *new_node = nullptr;
|
||||
Node<T>* new_node = nullptr;
|
||||
|
||||
try {
|
||||
new_node = new Node<T>;
|
||||
} 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;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user