-
destructors
In my program I have to put a destructor in the class which will delete all the links when a linklist object is distroyed. I have to delete each link as it goes, displaying a message that the element was destoryed.....this is the code for the class....
Code:
////////////////////////////////////////////////////////////////
struct link //one element of list
{
int data; //data item
link* next; //Pointer to next link
};
////////////////////////////////////////////////////////////////
class linklist
{
private:
link* first; //pointer to first link
public:
linklist() : first(NULL)
{ }
void additem(int d);
void display() const;
};
//--------------------------------------------------------------
void linklist::additem(int d)
{
link* newlink = new link; //make a new link
newlink->data = d; //give it data
newlink->next = first; //it points to next link
first = newlink; //now first points to this
}
//---------------------------------------------------------------
void linklist::display() const
{
link* current = first; //set ptr to first link
while(current != NULL) //quit on last link
{
cout<<current->data <<endl; //print data
current = current->next; //move to next link
}
}
////////////////////////////////////////////////////////////////
Anyhelp on where this destructor goes would be great.
Cheers
-
You'll need something like this:
Code:
if next
delete next
in the destructor, as well as the message displaying that the element was deleted. Figure out why this works - it's good for you.
Oh, and the placement of the destructor in the file doesn't matter.
void linklist::~linklist()
-
ive always been taught to do this with my linked lists:
you will probably want a function to remove a node from the end of your list. i would make its prototype like this:
template <typename Type>
bool remove( Type &t );
where type is the type of variable the list holds. the way it works is, you pass a variable in to t to store the data of the node youre deleting, and then you return true if a node was deleted or false if the list is empty.
then all you have to do in your destructor is call the remove function in a while loop until it returns false. i usually would make a dummy variable to hold the value, just so the function has the argument it needs.
Code:
List::~List()
{
Type temp
while ( remove(temp) );
}
-
how about something like:
Code:
while(count) // while there are nodes
{
RemoveNode; // call the function you normally call when deleting a node
//this should also decrement count
}
This is assuming you're keeping a counter in your list class of how many nodes you have.