diff --git a/DataStructures/src/linkedlist.h b/DataStructures/src/linkedlist.h index 29822cb..e58cf39 100644 --- a/DataStructures/src/linkedlist.h +++ b/DataStructures/src/linkedlist.h @@ -57,7 +57,9 @@ namespace Datastructures { 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 { + } + 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 @@ -66,12 +68,34 @@ namespace Datastructures { node->next = std::make_shared>(value, node->next); } - //Append the new value into a new node. mCount++; return true; } + template + bool LinkedList::remove(int index) { + //If the list is empty + if (this->mCount == 0) + return false; + + //Check if we are looking to remove the head node (0) + if (index == 0) + { + this->mHead = this->mHead->next; + } + else + { + //Get the node before the one that is about to be removed + std::shared_ptr> node = this->getIndex(index - 1); + //Point this node to the node pointed to by the one about to be removed + node->next = node->next->next; + } + //Reduce the total count of nodes + mCount--; + return true; + } + template std::shared_ptr> LinkedList::getIndex(int index) { //Check if the value lies within the range of the list. diff --git a/src/main.cpp b/src/main.cpp index 2af1764..8ea34ac 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -5,4 +5,5 @@ int main() { list.append(5); list.append(200); list.insert(20, 2); + list.remove(0); } \ No newline at end of file