Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Easy way of deleting linked lists?

Status
Not open for further replies.

thesleepylizard

Programmer
Mar 18, 2002
41
AU
Seems to me that an easy way of deleting linked lists is like this:

Code:
struct Item {
    Item () {
        Next = NULL;
    }
    ~Item () {
        if (Next) delete Next; //...which calls the destructor for the next object, which call the destructor for... etc
    }
    Item* MakeNext () {
        return Next = new Item(); //This is just a nicety too
    }
    Item* Next;
 
    int Member1;
    int Member2;
};


CurrentItem = FirstItem = new Item();
CurrentItem = CurrentItem->MakeNext();
CurrentItem = CurrentItem->MakeNext();
CurrentItem = CurrentItem->MakeNext();
CurrentItem = CurrentItem->MakeNext();

delete FirstItem; //Flies through ALL items!



Only downside to this is that each successive delete command will add another entry to the stack, and if you have thousands of linked lists this will be quite a lot of stack work, and certainly not suitable for an enterprise situation. OTOH, IMO linked lists shouldn't BE used for thousands of entries.

Any thoughts on this?

Cheers,
-lizard
 
>> IMO linked lists shouldn't BE used for thousands of
>> entries.

Usually, but not 100% of the time. It depends on the problem your solving with them. And if you had an appropriate use for a large linked list you wouldn't want to use recursion with it would you.

You can iterate a linked list without using recursion... yes?

-pete
 
Sure I can delete the linked list the "orthodox" way, it's just that the code is messy and difficult to read! My proposed way results in neater code (I think) but is not suitable for enterprise situations or long lists.

Oh well...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top