Created
September 22, 2019 20:18
-
-
Save danielgospodinow/f9e52c7ba9d6403b9e9ebc92ac414a60 to your computer and use it in GitHub Desktop.
Linked List get operation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Finds and returns an element by its index. | |
* | |
* @tparam T type | |
* @param index index of the required element. | |
* @return the element required | |
*/ | |
template<typename T> | |
T LinkedList<T>::get(const int index) const { | |
if (index < 0 || index >= _size) { | |
// If the index is out of bounds, throw an exception. | |
throw std::invalid_argument("Index out of bounds"); | |
} else { | |
// Initialize an index counter and a pointer to the head element. | |
int indexCounter = 0; | |
Node<T> *iter = _head; | |
// Move the pointer to point to the next element until we | |
// reach the desired index. | |
while (indexCounter++ < index) { | |
iter = iter->next; | |
} | |
// Then return that exact item. | |
return iter->elem; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment