diff --git a/DataStructures/src/linkedlist.h b/DataStructures/src/linkedlist.h index b365b06..9312013 100644 --- a/DataStructures/src/linkedlist.h +++ b/DataStructures/src/linkedlist.h @@ -51,37 +51,43 @@ namespace Datastructures { } //Add new node and set to tail. -<<<<<<< HEAD:DataStructures/src/linkedlist.h - mTail->mNext = std::make_shared>(value); - mTail = mTail->mNext; + mTail->next = std::make_shared>(value); + mTail = mTail->next; } template bool LinkedList::insert(T value, int index) { - std::shared_ptr> node = this->getIndex(index); - //If node is nullptr, index is out of range - if (node == nullptr) - return false; + + if (index == 0 || this->mCount == 0) + {//If the new item needs to go into the head of the linked list. + mHead = std::make_shared>(value, mHead); + } else { + //Get the node before the one we are going to be inserting + std::shared_ptr> node = this->getIndex(index-1); + //If node is nullptr, index is out of range + if (node == nullptr) + return false; + + node->next = std::make_shared>(value, node->next); + } //Append the new value into a new node. - node->mNext = std::make_shared>(value, node->mNext); + mCount++; + return true; } template std::shared_ptr> LinkedList::getIndex(int index) { //Check if the value lies within the range of the list. - if (index < 0 || index >= this->count()) + if (index < 0 || index >= this->mCount) return nullptr; std::shared_ptr> node = mHead; for (size_t i = 0; i < index; i++) {//Interate through the linked list i times to get to the index. - node = node->mNext; + node = node->next; } return node; -======= - (*mTail).next = std::make_shared>(value); - mTail = (*mTail).next; ->>>>>>> 700d6696c82b4ea8ba783238ef73b7efc630dd54:DataStructures/src/LinkedList/linkedlist.h + } } \ No newline at end of file diff --git a/src/main.cpp b/src/main.cpp index 4504b39..2af1764 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4,5 +4,5 @@ int main() { Datastructures::LinkedList list; list.append(5); list.append(200); - list.insert(20, 0); + list.insert(20, 2); } \ No newline at end of file