Skip to content

Instantly share code, notes, and snippets.

@danielgospodinow
Created September 22, 2019 20:11
Show Gist options
  • Save danielgospodinow/e01b9ef4eb76f67764196ad32129c0dc to your computer and use it in GitHub Desktop.
Save danielgospodinow/e01b9ef4eb76f67764196ad32129c0dc to your computer and use it in GitHub Desktop.
Linked List remove operation
/**
* Remove all elements from the data structure which match
* the item provided.
*
* @tparam T type
* @param item item to be removed
*/
template<typename T>
void LinkedList<T>::remove(const T &item) {
// Initialize pointers to two consecutive elements
// with the second one being the first element.
Node<T> *prev = nullptr;
Node<T> *curr = _head;
// Iterate through all two consecutive elements while the second of the two
// consecutive elements is not null.
while (curr) {
// If the current element's value is equal to the
// value we're looking for.
if (curr->elem == item) {
// If the current element is the first element in the data structure,
// then move the head with one position to the right.
if (curr == _head) {
// Check whether the head is equal to the tail.
// If so, move the tail, essentially making it null.
if (_head == _tail) {
_tail = _tail->next;
}
// Move the head element.
_head = _head->next;
}
// If the current element's previous element is not null,
// move it to the right.
if (prev) {
prev->next = curr->next;
}
if (curr == _tail) {
// If we happen to remove the last element,
// we should make the previous element the tail.
_tail = prev;
delete curr;
} else {
// Connect the current element's previous with the next element
// in the data structure and delete the current one.
Node<T> *temp = curr;
curr = curr->next;
delete temp;
}
// Reduce the size of the data structure.
--_size;
} else {
// If the current element's value is not equal
// to the value we're looking for, then just move both
// elements with one position to the right.
prev = curr;
curr = curr->next;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment