I wrote a recursive doubly linked C++ functions to delete all the nodes in a doubly linked list having a certain value. Is it possible to optimize this? Thank you.
struct marynode {
int value;
marynode* next;
marynode* prev;
};
void DoubleLinkedListDeleteMultiple(marynode*& llist, int value){
marynode* tmp = llist;
if (llist == NULL)
return;
if (llist->value == value){
DoubleLinkedListDeleteMultiple(llist->next, value);
if (llist->next == NULL){
marynode* prev = llist->prev;
delete llist;
llist = NULL;
llist = prev;
if (llist)
llist->next = 0;
}
else if (llist->prev == NULL){
marynode* next = llist->next;
delete llist;
llist = NULL;
llist = next;
if (llist)
llist->prev = 0;
}
else{
marynode *x = llist;
marynode *mynext = x->next;
while (x){
if (x->value == value){
marynode* clara = x->next;
marynode* zprev = x->prev;
delete x;
x = NULL;
x = clara;
llist = clara;
if (llist)
llist->prev = zprev;
}
else {
x = mynext;
}
if (mynext){
mynext = mynext->next;
}
}
}
}
else{
DoubleLinkedListDeleteMultiple(llist->next, value);
}
}
Is something wrong with std::list?
Also, structs + global functions? You probably want to use object oriented constructs like member methods instead.
To optimize this particular code a little, I’d change your recursive call to a while loop.