#1 Moved datastructures directly into src directory and added insert method to linked list
This commit is contained in:
parent
05d637acb5
commit
32a5a1c51a
@ -9,6 +9,7 @@ namespace Datastructures {
|
||||
public:
|
||||
//Inherit Constructor and destructor from generic Undirectetd Node
|
||||
using Generic::UndirectedNode<T, LinkedListNode<T>>::UndirectedNode;
|
||||
|
||||
template <typename T>
|
||||
friend class LinkedList;
|
||||
private:
|
@ -1,5 +1,5 @@
|
||||
#pragma once
|
||||
#include "linkedlistnode.h"
|
||||
#include "Nodes/linkedlistnode.h"
|
||||
|
||||
namespace Datastructures {
|
||||
template <typename T>
|
||||
@ -9,12 +9,14 @@ namespace Datastructures {
|
||||
LinkedList();
|
||||
LinkedList(T value);
|
||||
~LinkedList();
|
||||
T operator[](int index);
|
||||
void append(T value);
|
||||
bool insert(T value, int index);
|
||||
bool remove(int index);
|
||||
int count() const;
|
||||
|
||||
private:
|
||||
std::shared_ptr<Nodes::LinkedListNode<T>> getIndex(int index);
|
||||
std::shared_ptr<Nodes::LinkedListNode<T>> mHead;
|
||||
std::shared_ptr<Nodes::LinkedListNode<T>> mTail;
|
||||
int mCount;
|
||||
@ -49,7 +51,32 @@ namespace Datastructures {
|
||||
}
|
||||
|
||||
//Add new node and set to tail.
|
||||
(*mTail).mNext = std::make_shared<Nodes::LinkedListNode<T>>(value);
|
||||
mTail = (*mTail).mNext;
|
||||
mTail->mNext = std::make_shared<Nodes::LinkedListNode<T>>(value);
|
||||
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;
|
||||
}
|
||||
}
|
@ -1,7 +1,8 @@
|
||||
#include <LinkedList/linkedlist.h>
|
||||
#include <linkedlist.h>
|
||||
|
||||
int main() {
|
||||
Datastructures::LinkedList<int> list;
|
||||
list.append(5);
|
||||
list.append(200);
|
||||
list.insert(20, 0);
|
||||
}
|
Loading…
Reference in New Issue
Block a user