Last active
May 31, 2019 22:09
-
-
Save xseano/3e802823dd68ee914e1f9bdc3cdc45a7 to your computer and use it in GitHub Desktop.
Linked List Remove Node
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
/** | |
* @brief Remove Node of data "T" from end of list | |
* | |
* @param targetData the data to remove from the list | |
*/ | |
template <class T> | |
void LinkedList<T>::removeNode(T targetData) | |
{ | |
if (head<T> == NULL) | |
{ | |
// check to make sure there is actual data in the list | |
return; | |
} | |
Node<T> *tmp = head<T>; // obtain the head node | |
Node<T> *prev = NULL; | |
while(tmp->next != head<T>) // while the next ptr doesnt point to the head (aka iterate to tail) | |
{ | |
if (tmp->data == targetData) // if we hit the requested data, break the loop | |
{ | |
break; | |
} | |
prev = tmp; | |
tmp = tmp->next; // iterate next node until we hit the data | |
} | |
if(tmp->data != targetData) | |
{ | |
// if the data doesn't exist in the list, this will happen | |
return; | |
} | |
if(tmp == head<T>) // if the data is found to be the head node | |
{ | |
while(tmp->next != head<T>) | |
{ | |
tmp = tmp->next; // reassign the temporary node | |
} | |
tmp->next = head<T>->next; // store the head's next node so we can reassign after destruction of the Node | |
delete head<T>; // delete the head node which matches this data | |
head<T> = tmp->next; // set the NEW head to the next element after the now-deleted node | |
} | |
else | |
{ | |
prev->next = tmp->next; // store the Node's next ptr | |
delete tmp; | |
} | |
return; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment