#1 Updated insert method on Linked List to work with index 0

This commit is contained in:
Luke Else 2022-11-21 14:18:34 +00:00
parent 7cabc13196
commit e338ddb255
2 changed files with 21 additions and 15 deletions

View File

@ -51,37 +51,43 @@ namespace Datastructures {
} }
//Add new node and set to tail. //Add new node and set to tail.
<<<<<<< HEAD:DataStructures/src/linkedlist.h mTail->next = std::make_shared<Nodes::LinkedListNode<T>>(value);
mTail->mNext = std::make_shared<Nodes::LinkedListNode<T>>(value); mTail = mTail->next;
mTail = mTail->mNext;
} }
template <typename T> template <typename T>
bool LinkedList<T>::insert(T value, int index) { bool LinkedList<T>::insert(T value, int index) {
std::shared_ptr<Nodes::LinkedListNode<T>> node = this->getIndex(index);
//If node is nullptr, index is out of range if (index == 0 || this->mCount == 0)
if (node == nullptr) {//If the new item needs to go into the head of the linked list.
return false; mHead = std::make_shared<Nodes::LinkedListNode<T>>(value, mHead);
} else {
//Get the node before the one we are going to be inserting
std::shared_ptr<Nodes::LinkedListNode<T>> node = this->getIndex(index-1);
//If node is nullptr, index is out of range
if (node == nullptr)
return false;
node->next = std::make_shared<Nodes::LinkedListNode<T>>(value, node->next);
}
//Append the new value into a new node. //Append the new value into a new node.
node->mNext = std::make_shared<Nodes::LinkedListNode<T>>(value, node->mNext); mCount++;
return true;
} }
template <typename T> template <typename T>
std::shared_ptr<Nodes::LinkedListNode<T>> LinkedList<T>::getIndex(int index) { std::shared_ptr<Nodes::LinkedListNode<T>> LinkedList<T>::getIndex(int index) {
//Check if the value lies within the range of the list. //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; return nullptr;
std::shared_ptr<Nodes::LinkedListNode<T>> node = mHead; std::shared_ptr<Nodes::LinkedListNode<T>> node = mHead;
for (size_t i = 0; i < index; i++) for (size_t i = 0; i < index; i++)
{//Interate through the linked list i times to get to the index. {//Interate through the linked list i times to get to the index.
node = node->mNext; node = node->next;
} }
return node; return node;
=======
(*mTail).next = std::make_shared<Nodes::LinkedListNode<T>>(value);
mTail = (*mTail).next;
>>>>>>> 700d6696c82b4ea8ba783238ef73b7efc630dd54:DataStructures/src/LinkedList/linkedlist.h
} }
} }

View File

@ -4,5 +4,5 @@ int main() {
Datastructures::LinkedList<int> list; Datastructures::LinkedList<int> list;
list.append(5); list.append(5);
list.append(200); list.append(200);
list.insert(20, 0); list.insert(20, 2);
} }