user1665569
user1665569

Reputation: 191

Destructor for a linked List

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;
}
}

Upvotes: 0

Views: 26679

Answers (3)

Pranav Prakasan
Pranav Prakasan

Reputation: 21

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.

Upvotes: 0

HenryLok
HenryLok

Reputation: 81

change to

 linked_list::~linked_list(void)
{
struct node *next;
while (first != NULL)
{
    next = first->next;
    delete first;
    first = next;
}
 }

Upvotes: 1

user123
user123

Reputation: 9071

The problem lies here:

delete first;
first = first->next;

When you delete first, but then try to access first->next. Cache first->next into a temp variable of type node*, then do delete first to fix this:

struct node* temp;
while (first != NULL)
{
    temp = first->next;
    delete first;
    first = temp;
}

Upvotes: 9

Related Questions