I am trying to remove duplicates from a linked list, and encountered a problem, which is probably obvious and straightforward but I haven\'t used C++
in many years
This is an addendum to other answers which correctly identify and solve the OP's immediate problem. A quick walk-though is required to explain what will happen next.
Node *temp = cur;
prev->next = cur->next;
cur = cur->next;
cur->prev = prev;
At this point temp has not been cleared so next and prev still point to the two nodes that used to surround cur and are now linked together. This will cause serious problems if not for:
free(temp); //Here is my problem!!!
free
fails because the value pointed to by temp was allocated by new. NathanOliver's answer has this covered, but lurking beneath is what will happen with
delete temp;
This will invoke the destructor to clean up like a good little object. Unfortunately the Node
destructor looks like this:
~Node() { delete next; delete prev; }
temp->next
still points to a live node. So does temp->prev
.
Next and prev get delete
d. Which calls their destructors, delete
ing the two nodes they touch, and invokes a deathstorm that will destroy all of the Nodes in the list.
If the double-deletes don't kill the program first. Each linked node will try to delete
the node that just deleted
them. Not good.
Odds are pretty good that the Node
destructor should just look after itself and leave the destruction of the other Node
s to the LinkedList
class.