1. ## Freeing a linked list

This is a very specific and detailed question, but at the end of this free method will my pAhead pointer need to be deleted since it should point to NULL?
Code:
NODE * pAhead = pList->next;
{
delete pList;
}
delete pList;

2. You might find a conditional recursive function better for that than a while loop, because it will ensure that the list is deleted in reverse order. This will cause your list to delete back to front and keep you from having to copy your pointers to a temp variable.

Something like
Code:
void kill (list_node *gone) {
if (gone != NULL) {
kill (gone->next);
delete gone;
}
}
I'm away from my compiler but from memory that should work.

3. If it's NULL, then no but you can safely delete NULL pointers.

Why not do -

NODE* pTemp;
{
delete pTemp;
}

4. Good idea, so I can make a 50000 node list and use a recursive function to free it all. I'm sure recursion is okay for small lists, but my question has nothing to do with the actual method of freeing the list as much as a detail of that method.

5. Sure ya could CC, you would just need to put in some outer recursions before you started deleting things, take your nodes about half a stack at a time.

Also, please don't be rude to people who are trying to help you. You could simply have said "That won't work for my problem"

6. Sorensen:
Thank you, but isn't your loop the same as mine in functionality except for which pointer it frees? If there's a favorable difference I'll start doing it that way.

Imperito:
I wasn't trying to be rude, I'm sorry. However this isn't part of a program that I'm writing, it was merely a question that popped up while I was sitting around and I was curious.

Also, I understand freeing lists with recursion but it always struck me as horribly inefficient while a loop tends to be simpler and faster. Can you explain why I should use recursion over iteration?

7. I've always used recursion because if there is a problem, you still have the address of the head. If you go deleting front to back, you change the address of the head each iteration and if something bad happens you could end up with a pointer to a deleted node and no way of finding the next one. Deleting back to front leaves the head until last.

Or you could just use the STL vector, if feasable.

8. >isn't your loop the same as mine in functionality except for which pointer it frees

Yes, it's just re-arranged so you don't have to do some of the work outside of the loop which may confuse things. You didn't seem sure what had been deleted in the method you were using.

Popular pages Recent additions