#1 Added find function to Linked List

This commit is contained in:
Luke Else 2022-11-22 20:53:37 +00:00
parent 84645fad5f
commit 15c4684857
2 changed files with 20 additions and 1 deletions

View File

@ -14,6 +14,11 @@ namespace Datastructures {
bool insert(T value, int index);
bool remove(int index);
int count() const;
int find(const T &value) const;
enum EFindResult {
eNotFound = -1,
};
private:
std::shared_ptr<Nodes::LinkedListNode<T>> getIndex(int index);
@ -96,6 +101,19 @@ namespace Datastructures {
return true;
}
template <typename T>
int LinkedList<T>::find(const T& value) const {
//Start at the head of the list
std::shared_ptr<Nodes::LinkedListNode<T>> node = mHead;
for (int i = 0; i < this->mCount; i++)
{//Loop through list to try and find value
if (node->value == value)
return i;
node = node->next;
}
return EFindResult::eNotFound; //-1
}
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.
@ -103,7 +121,7 @@ namespace Datastructures {
return nullptr;
std::shared_ptr<Nodes::LinkedListNode<T>> node = mHead;
for (size_t i = 0; i < index; i++)
for (int i = 0; i < index; i++)
{//Interate through the linked list i times to get to the index.
node = node->next;
}

View File

@ -6,4 +6,5 @@ int main() {
list.append(200);
list.insert(20, 2);
list.remove(0);
int x = list.find(10);
}