#1 Added find function to Linked List
This commit is contained in:
parent
84645fad5f
commit
15c4684857
@ -14,6 +14,11 @@ namespace Datastructures {
|
|||||||
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;
|
||||||
|
int find(const T &value) const;
|
||||||
|
|
||||||
|
enum EFindResult {
|
||||||
|
eNotFound = -1,
|
||||||
|
};
|
||||||
|
|
||||||
private:
|
private:
|
||||||
std::shared_ptr<Nodes::LinkedListNode<T>> getIndex(int index);
|
std::shared_ptr<Nodes::LinkedListNode<T>> getIndex(int index);
|
||||||
@ -96,6 +101,19 @@ namespace Datastructures {
|
|||||||
return true;
|
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>
|
template <typename T>
|
||||||
std::shared_ptr<Nodes::LinkedListNode<T>> LinkedList<T>::getIndex(int index) {
|
std::shared_ptr<Nodes::LinkedListNode<T>> LinkedList<T>::getIndex(int index) {
|
||||||
//Check if the value lies within the range of the list.
|
//Check if the value lies within the range of the list.
|
||||||
@ -103,7 +121,7 @@ namespace Datastructures {
|
|||||||
return nullptr;
|
return nullptr;
|
||||||
|
|
||||||
std::shared_ptr<Nodes::LinkedListNode<T>> node = mHead;
|
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.
|
{//Interate through the linked list i times to get to the index.
|
||||||
node = node->next;
|
node = node->next;
|
||||||
}
|
}
|
||||||
|
@ -6,4 +6,5 @@ int main() {
|
|||||||
list.append(200);
|
list.append(200);
|
||||||
list.insert(20, 2);
|
list.insert(20, 2);
|
||||||
list.remove(0);
|
list.remove(0);
|
||||||
|
int x = list.find(10);
|
||||||
}
|
}
|
Loading…
Reference in New Issue
Block a user