Member Avatar for icewizard

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

Recommended Answers

All 2 Replies

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.

Member Avatar for icewizard

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.