#1 Updated insert method on Linked List to work with index 0
This commit is contained in:
parent
7cabc13196
commit
e338ddb255
@ -51,37 +51,43 @@ namespace Datastructures {
|
||||
}
|
||||
|
||||
//Add new node and set to tail.
|
||||
<<<<<<< HEAD:DataStructures/src/linkedlist.h
|
||||
mTail->mNext = std::make_shared<Nodes::LinkedListNode<T>>(value);
|
||||
mTail = mTail->mNext;
|
||||
mTail->next = std::make_shared<Nodes::LinkedListNode<T>>(value);
|
||||
mTail = mTail->next;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
bool LinkedList<T>::insert(T value, int index) {
|
||||
std::shared_ptr<Nodes::LinkedListNode<T>> node = this->getIndex(index);
|
||||
|
||||
if (index == 0 || this->mCount == 0)
|
||||
{//If the new item needs to go into the head of the linked list.
|
||||
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.
|
||||
node->mNext = std::make_shared<Nodes::LinkedListNode<T>>(value, node->mNext);
|
||||
mCount++;
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
std::shared_ptr<Nodes::LinkedListNode<T>> LinkedList<T>::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<Nodes::LinkedListNode<T>> 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<Nodes::LinkedListNode<T>>(value);
|
||||
mTail = (*mTail).next;
|
||||
>>>>>>> 700d6696c82b4ea8ba783238ef73b7efc630dd54:DataStructures/src/LinkedList/linkedlist.h
|
||||
|
||||
}
|
||||
}
|
@ -4,5 +4,5 @@ int main() {
|
||||
Datastructures::LinkedList<int> list;
|
||||
list.append(5);
|
||||
list.append(200);
|
||||
list.insert(20, 0);
|
||||
list.insert(20, 2);
|
||||
}
|
Loading…
Reference in New Issue
Block a user