I know it is possible to free a singly linked list like below:
void freeList(struct n** head)
{
struct n* tmp;
while (*head != NULL)
{
tmp = *head;
*head = (*head)->next;
free(tmp);
}
*head = NULL;
}
The above code works perfectly and can be said to be simple enough for its purpose. Is it, however, possible to achieve the same with a for loop instead of a while loop? I have tried alot of quirks but don't seem to getting anywhere.
CodePudding user response:
There are a few ways, for example:
void freeList(struct n** head)
{
for(struct n *tmp = *head; tmp; tmp = *head) {
{
*head = tmp->next;
free(tmp);
}
}
However, your while loop is (arguably) easier to read and understand, though it can be simplified:
void freeList(struct n** head)
{
// moving struct n* tmp to smallest possible scope, in the loop
while (*head != NULL)
{
struct n *tmp = *head;
*head = tmp->next;
free(tmp);
}
// removing *head = NULL because while loop end condition already guarantees this
}
