Linkedlist bugfixes

This commit is contained in:
2019-05-01 21:29:51 +02:00
parent 64fa2f30ab
commit e1138917b4

View File

@@ -27,33 +27,35 @@ protected:
public:
void Append(T const value)
{
++size;
if(tailPtr == nullptr)
if(size == 0)
{
root = std::make_unique<Node<T>>(value);
tailPtr = root.get();
++size;
return;
}
tailPtr->next = std::make_unique<Node<T>>(value);
tailPtr = tailPtr->next.get();
++size;
}
void Prepend(T const value)
{
++size;
if(root == nullptr)
if(size == 0)
{
root = std::make_unique<Node<T>>(value);
tailPtr = root.get();
++size;
return;
}
auto newRoot = std::make_unique<Node<T>>(value);
newRoot->next.swap(root);
root.swap(newRoot);
++size;
}
void Insert(T const value, std::size_t const index)
@@ -69,12 +71,6 @@ public:
return;
}
if(index == size - 1u)
{
Append(value);
return;
}
++size;
Node<T> * prevPtr = root.get();
@@ -83,7 +79,8 @@ public:
while(currentIndex < index)
{
prevPtr = curPtr;
curPtr = curPtr->next().get();
curPtr = curPtr->next.get();
++currentIndex;
}
auto newNode = std::make_unique<Node<T>>(value);
@@ -102,33 +99,43 @@ public:
if(index == 0u)
{
root.swap(root->next);
if(size == 0u)
{
root.release();
tailPtr = nullptr;
}
else
{
root = std::move(root->next);
}
return;
}
if(index == size - 1u)
// Is index last element? Note that we subtracted 1 from size above
if(index == size)
{
Node<T> * curPtr = root.get();
std::size_t currentIndex = 0u;
while(currentIndex < index - 2u)
while(curPtr->next.get() != tailPtr)
{
curPtr = curPtr->next().get();
curPtr = curPtr->next.get();
}
curPtr->next.release();
tailPtr = curPtr;
tailPtr->next.release();
return;
}
Node<T> * prevPtr = root.get();
Node<T> * curPtr = root->next.get();
Node<T> * curPtr = prevPtr->next.get();
std::size_t currentIndex = 1u;
while(currentIndex < index)
{
++currentIndex;
prevPtr = curPtr;
curPtr = curPtr->next().get();
curPtr = curPtr->next.get();
}
prevPtr->next.swap(curPtr->next);
prevPtr->next = std::move(curPtr->next);
}
T & Front()
@@ -159,18 +166,25 @@ public:
}
Node<T> * currentNode = root.get();
std:size_t currentIndex = 0u;
std::size_t currentIndex = 0u;
while(currentIndex < index)
{
currentNode = currentNode->next.get();
++currentIndex;
}
return currentNode->value;
}
std::size_t GetSize() const
{
return size;
}
List()
: root(nullptr),
tailPtr(nullptr)
tailPtr(nullptr),
size(0)
{}
};
}