0

For a given list, I would like my output to have the line "Deleting node with value ..." for each node.

My destructor function works for a 2-element list, but for a 3-element list it deletes a certain node more than once, and for a list of any size greater than 3, I get an infinite loop. I try tracing through the code, but I am not sure what is going on. Any suggestions? Thanks.

#include <iostream>
#include <cassert>
#include "lists.h"

using namespace std;

ListNode::ListNode (int k) {
    myValue = k;
    myNext = 0;
}

ListNode::ListNode (int k, ListNode* ptr) {
    myValue = k;
    myNext = ptr;
}

ListNode::~ListNode () {
    cout << "Deleting node with value " << myValue << endl;

    for (ListNode* p=this; p!=0; ){
        p=p->myNext;
        delete p;
        }
}
2
Contributors
2
Replies
3
Views
9 Years
Discussion Span
Last Post by icewizard
0
for (ListNode* p=this; p!=0; ){
  p=p->myNext;
  delete p;
}

Yea, that's kind of scary. First, when you delete p, you're calling the destructor... Second, why in the world is your node class performing a list operation? Your node shouldn't give a hoot about other nodes, that's something your list class is in a better position to deal with.

0

I'm actually working with just one class called ListNode. I changed my destructor function to look like this.

ListNode::~ListNode () {
cout << "Deleting node with value " << myValue << endl;

//this automatically stops when p points to 0, seems to be just stepping through the list?
ListNode* p = this;
p=p->myNext;
delete p;
}

It works now, but I'm not completely sure why. It seems like the function is simply stepping through the list, but when I view the contents of the list after the deletion, there are now garbage values in all the nodes. Given that I am only working with one class, is this the right way to do it? Thanks.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.