• Some users have recently had their accounts hijacked. It seems that the now defunct EVGA forums might have compromised your password there and seems many are using the same PW here. We would suggest you UPDATE YOUR PASSWORD and TURN ON 2FA for your account here to further secure it. None of the compromised accounts had 2FA turned on.
    Once you have enabled 2FA, your account will be updated soon to show a badge, letting other members know that you use 2FA to protect your account. This should be beneficial for everyone that uses FSFT.

C++: LinkedList destructor

Stupendous

[H]ard|Gawd
Joined
Aug 29, 2000
Messages
1,370
Kinda new to C++ so I wanna see if this is right

A Node has a pointer to an item and the next node. For the destructor I just want to free the memory allocated for all the Nodes and not the data.

Is this correct?

Code:
class L
{
  Node *head;

  L::~L()
  {
    for(Node *c = head; c != NULL; c = c->next){
      delete c;
    }
  }
};
 
No that is not correct. Your code will delete the root node, and then run into problems. Think, how is your code supposed to find the next node if you have just deleted the information pointing to the next node?

What you need to do is delete the final node first, and then move towards the front. Assuming that Node is a struct (if it is a class, you could do this even more elegantly) the code could look something like this:

Code:
L::~L() {
     delete_node(head);
}

L::delete_node(Node * input_node) {
     delete_node(input_node->next);
     delete input_node;
}

Also, I know that was a very general class outline, but there are many things wrong with it, but I will leave it up to you to find those out.
 
Doh, yeah I see that now.

This should work then?

Code:
for(Node *c = head; c != NULL; ){
  Node *p = c;
  c = c->next;
  delete p;
}
 
you've got the right idea. here is how I do it

Code:
Node* node = head;
Node* next;
while( node )
{
    next = node->next;
    delete node;
    node = next;
}
 
Back
Top