Here is a short insert on how to remove all Nodes of X value from a list. I use recursion and I believe I’ve created a pretty clean solution. This requires Nodes found in my earlier post.
#include "Node.h" Node* head; //contains the head of our linked list //Run the search and remove on the linked list starting at the head //target is the value we are trying to remove from our list void searchAndRemove(int target){ searchAndRemove(target, head); } void searchAndRemove(int target, Node*& n){ if(n != nullptr){ if(n->data == target) { //if we found our target Node* temp = n; n = n->next; //delete and replace delete temp; //delete the node to clean up memory searchAndRemove(target, n); //continue the search, we need this to check the one used to replace } else { searchAndRemove(target, n->next); //continue the search } } }
Let me know if you have any comments or improvements!