To free the memory of a link list so I have to travel though each node and free it?
To free the memory of a link list so I have to travel though each node and free it?
Of course you do. For every malloc call, you need a free call.Originally Posted by EvilBaby
Quzah.
Hope is the first step on the road to disappointment.
Originally Posted by quzah
damn, my link list is 45 000 + links, this is gonna take a while
just out of curiosity should this work
Code:while (current != NULL) { if (current->next != NULL) { temp = current->next; free (current); current = temp; } else free(current); }
Normally you'd do something like this
Code:while (current) { temp = current->next; free(current); current = temp; }
When all else fails, read the instructions.
If you're posting code, use code tags: [code] /* insert code here */ [/code]
>damn, my link list is 45 000 + links, this is gonna take a while
45,000+ really isn't that much for any realistic application.
My best code is written with the delete key.
thanks for the help
Originally Posted by Prelude
it is when you were tyring to do it the way I originally thought I had to. See I'm new at this so I started off by going to the last element, free, that, then go through the list to the last element again and free that and do that over 45 000 times.
However I soon realized there was a much better way of doing it and as it turns out I was almost right.
Yea if you are trying to free the last element everytime it'll take a while. The "standard" way is to free the head.
>Yea if you are trying to free the last element everytime it'll take a while
Only if you don't have a tail pointer and a double linked list or a suitable single linked setup for tail deletion.
>I started off by going to the last element, free
Yikes. Yes, that would be rather inefficient for a list of that size.
My best code is written with the delete key.
And just because...
But on a very big list you may run out of stack space.Code:void nocircularlistsplease(struct node*n) { if(n&&n->next) nocircularlistsplease(n->next); free(n); }
Quzah.
Hope is the first step on the road to disappointment.