I have a linked_list and currently my destructor is not working properly. Not entirely sure why. Can somebody explain me how to solve this?
class linked_list {
private:
struct node
{
// String in this node
std::string data;
// Pointer to next node
struct node *next;
};
//First item in the list
struct node *first;
Here is my destructor
linked_list::~linked_list(void)
{
while (first)
{
delete first;
first = first->next;
}
}
When you 'delete' first, you actually clear all the links from it. Now, if you try to access some other node using this, will not produce the required result.
First, you have to point that node with some other pointer, so that you still have some link which you can access later.
change to
The problem lies here:
When you delete
first
, but then try to accessfirst->next
. Cachefirst->next
into a temp variable of typenode*
, then dodelete first
to fix this: