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