Skip to content

Instantly share code, notes, and snippets.

@danielgospodinow
Created September 22, 2019 20:12
Show Gist options
  • Save danielgospodinow/af70e4603b6a027ac1f31823ea7f2607 to your computer and use it in GitHub Desktop.
Save danielgospodinow/af70e4603b6a027ac1f31823ea7f2607 to your computer and use it in GitHub Desktop.
Linked List removeAt operation
/**
* Remove an element from a specified index.
*
* @tparam T type
* @param index index of an element
*/
template<typename T>
void LinkedList<T>::removeAt(const int index) {
if (index < 0 || index >= _size) {
// If the index is out of bounds, throw an exception.
throw std::invalid_argument("Index out of bounds");
} else {
// Create an index counter and two pointers which
// we'll use to keep track of every two consecutive
// elements in the data structure.
int indexCounter = 0;
Node<T> *prev = nullptr;
Node<T> *iter = _head;
// Iterate through elements util
// the desired element index is reached.
while (indexCounter++ < index) {
prev = iter;
iter = iter->next;
}
if (prev && iter) {
// If both consecutive elements exist this means
// that we're surely somewhere after the first
// element.
// Check whether we're trying to delete the last element.
// If so, make the previous the new tail.
if(iter == _tail) {
_tail = prev;
}
// Break the connection between the two consecutive
// elements and make the first one point to the
// second one's next element, thus preparing the
// second element for deletion.
prev->next = iter->next;
// Reduce the size of the data structure by 1 and
// delete the second of the two consecutive elements.
--_size;
delete iter;
} else if (iter) {
// If only the second of the two consecutive elements
// exist, this means that we're at the beginning of
// the data structure. In this case we need to move
// the head with one position.
_head = _head->next;
// Reduce the size of the data structure by 1 and
// delete the second of the two consecutive elements.
--_size;
delete iter;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment