#1 Moved datastructures directly into src directory and added insert method to linked list

This commit is contained in:
Luke Else 2022-11-21 13:41:51 +00:00
parent 05d637acb5
commit 32a5a1c51a
3 changed files with 33 additions and 4 deletions

View File

@ -9,6 +9,7 @@ namespace Datastructures {
public: public:
//Inherit Constructor and destructor from generic Undirectetd Node //Inherit Constructor and destructor from generic Undirectetd Node
using Generic::UndirectedNode<T, LinkedListNode<T>>::UndirectedNode; using Generic::UndirectedNode<T, LinkedListNode<T>>::UndirectedNode;
template <typename T> template <typename T>
friend class LinkedList; friend class LinkedList;
private: private:

View File

@ -1,5 +1,5 @@
#pragma once #pragma once
#include "linkedlistnode.h" #include "Nodes/linkedlistnode.h"
namespace Datastructures { namespace Datastructures {
template <typename T> template <typename T>
@ -9,12 +9,14 @@ namespace Datastructures {
LinkedList(); LinkedList();
LinkedList(T value); LinkedList(T value);
~LinkedList(); ~LinkedList();
T operator[](int index);
void append(T value); void append(T value);
bool insert(T value, int index); bool insert(T value, int index);
bool remove(int index); bool remove(int index);
int count() const; int count() const;
private: private:
std::shared_ptr<Nodes::LinkedListNode<T>> getIndex(int index);
std::shared_ptr<Nodes::LinkedListNode<T>> mHead; std::shared_ptr<Nodes::LinkedListNode<T>> mHead;
std::shared_ptr<Nodes::LinkedListNode<T>> mTail; std::shared_ptr<Nodes::LinkedListNode<T>> mTail;
int mCount; int mCount;
@ -49,7 +51,32 @@ namespace Datastructures {
} }
//Add new node and set to tail. //Add new node and set to tail.
(*mTail).mNext = std::make_shared<Nodes::LinkedListNode<T>>(value); mTail->mNext = std::make_shared<Nodes::LinkedListNode<T>>(value);
mTail = (*mTail).mNext; mTail = mTail->mNext;
}
template <typename T>
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 (node == nullptr)
return false;
//Append the new value into a new node.
node->mNext = std::make_shared<Nodes::LinkedListNode<T>>(value, node->mNext);
}
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())
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;
}
return node;
} }
} }

View File

@ -1,7 +1,8 @@
#include <LinkedList/linkedlist.h> #include <linkedlist.h>
int main() { 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);
} }