From e1138917b4ed79027a13af837a9e94735d81a492 Mon Sep 17 00:00:00 2001 From: Tijmen van Nesselrooij Date: Wed, 1 May 2019 21:29:51 +0200 Subject: [PATCH] Linkedlist bugfixes --- sequential/linkedlist.hpp | 62 ++++++++++++++++++++++++--------------- 1 file changed, 38 insertions(+), 24 deletions(-) diff --git a/sequential/linkedlist.hpp b/sequential/linkedlist.hpp index 7c9d3d9..9713a89 100644 --- a/sequential/linkedlist.hpp +++ b/sequential/linkedlist.hpp @@ -27,33 +27,35 @@ protected: public: void Append(T const value) { - ++size; - - if(tailPtr == nullptr) + if(size == 0) { root = std::make_unique>(value); tailPtr = root.get(); + ++size; return; } tailPtr->next = std::make_unique>(value); tailPtr = tailPtr->next.get(); + + ++size; } void Prepend(T const value) { - ++size; - - if(root == nullptr) + if(size == 0) { root = std::make_unique>(value); tailPtr = root.get(); + ++size; return; } auto newRoot = std::make_unique>(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 * 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>(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 * 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 * prevPtr = root.get(); - Node * curPtr = root->next.get(); + Node * 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 * 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) {} }; }