diff --git a/DataStructures/src/LinkedList/linkedlistnode.h b/DataStructures/src/Nodes/linkedlistnode.h similarity index 99% rename from DataStructures/src/LinkedList/linkedlistnode.h rename to DataStructures/src/Nodes/linkedlistnode.h index e0f3d73..0a08bb8 100644 --- a/DataStructures/src/LinkedList/linkedlistnode.h +++ b/DataStructures/src/Nodes/linkedlistnode.h @@ -9,6 +9,7 @@ namespace Datastructures { public: //Inherit Constructor and destructor from generic Undirectetd Node using Generic::UndirectedNode>::UndirectedNode; + template friend class LinkedList; private: diff --git a/DataStructures/src/LinkedList/linkedlist.h b/DataStructures/src/linkedlist.h similarity index 51% rename from DataStructures/src/LinkedList/linkedlist.h rename to DataStructures/src/linkedlist.h index e48d05d..cbee965 100644 --- a/DataStructures/src/LinkedList/linkedlist.h +++ b/DataStructures/src/linkedlist.h @@ -1,5 +1,5 @@ #pragma once -#include "linkedlistnode.h" +#include "Nodes/linkedlistnode.h" namespace Datastructures { template @@ -9,12 +9,14 @@ namespace Datastructures { LinkedList(); LinkedList(T value); ~LinkedList(); + T operator[](int index); void append(T value); bool insert(T value, int index); bool remove(int index); int count() const; private: + std::shared_ptr> getIndex(int index); std::shared_ptr> mHead; std::shared_ptr> mTail; int mCount; @@ -49,7 +51,32 @@ namespace Datastructures { } //Add new node and set to tail. - (*mTail).mNext = std::make_shared>(value); - mTail = (*mTail).mNext; + mTail->mNext = std::make_shared>(value); + mTail = mTail->mNext; + } + + 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; + + //Append the new value into a new node. + node->mNext = std::make_shared>(value, node->mNext); + } + + 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()) + 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; + } + return node; } } \ No newline at end of file diff --git a/src/main.cpp b/src/main.cpp index e40fb24..4504b39 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,7 +1,8 @@ -#include +#include int main() { Datastructures::LinkedList list; list.append(5); list.append(200); + list.insert(20, 0); } \ No newline at end of file