"Timothy Madden" <ba****@rmv.spam.home.ro> escribió en el mensaje
news:2r*************@uni-berlin.de...
Hello
I have a linked list of object of a class. I thought it would be nice to
have the destructor delete the whole list when I delete just the first
element. I don't want to recursivly destroy the list elements; the list is
arbitrary long. Something like this:
class ListElem
{
char Datum[1000];
class ListElem *Next;
ListElem()
{ Next = NULL; }
~ListElem()
{
class ListElem *el;
while (Next)
{
el = Next;
Next = Next->Next;
delete el;
}
}
}
but the last instruction delete el; will make a recursive call to the
destructor and it's all going down.
How can I delete an element, from the destructor, without calling the
destructor again ?
Thank you
Timothy Madden
Romania
---------------------------------------------
And I don't wanna miss a thing
I agree with Victor Bazarov, in the fact that your problem comes from a bad
design of your list. Yes, it seems to be simpler, faster and clearer, but
that is not truth, and your problem is enough prove of this. The
(simple-linked) list is an entity itself, and so it should be implemented as
a class other than ListElem. Though an element provides the functionality to
organize it inside a list, it's not the entire list, but just a single
element.
Also, you should consider a third class, an iterator, which manages a single
traversal over the list. Because you can have an arbitrary number of
simultaneous traversals over a same list, this functionality can not be
included inside the list itself (and again, it's not responsibility of a
single element).
Last, think that a single-linked list is one of the simplest data
structures. Things I comment here gain in relevance as the complexity levels
grows up.
But returning to your question, here is a solution which deletes the entire
list in the way that you want to do it, avoiding those problems derived from
recursion. There is still a recursion, which is unavoidable with your
scheme, but it's only a two-level recursion.
~ListElem()
{
ListElem * el;
while (Next)
{
el = Next;
Next = Next->Next;
el->Next = NULL; // This is enough to ensure that the list will
be not recursively traversed.
delete el;
}
}