user12239061
user12239061

Reputation:

Delete all nodes linked list

In this function:

void final_delete(node **head) {
    node *tmp;

    tmp = *head;

    while (tmp != NULL) {
        tmp = tmp->next;
        free(*head);
        *head = tmp;
    }
    *head = tmp;             //<-------- HERE
}

Is the reported part necessary? *head = tmp isn't it already the last step of the while loop?

Upvotes: 2

Views: 59

Answers (3)

chqrlie
chqrlie

Reputation: 145307

The statement is indeed redundant: tmp will be a null pointer at the end of the loop but either *head was already null before the loop or is was set to NULL during the last iteration of the loop.

Here is more readable version:

void final_delete(node **head) {
    while (*head != NULL) {
        node *tmp = *head;
        *head = tmp->next;
        free(tmp);
    }
}

Upvotes: 1

Yunnosch
Yunnosch

Reputation: 26763

Well, the loop might not be iterated at all, in case that tmp is NULL.
In that case the last line ensures that *head is updated to NULL.
So your reason is not all of the explanation.
The last line only becomes unneeded because of your reason plus the fact that the loop only is never iterated if tmp became NULL via *head being NULL already, and THAT makes the last line unneeded.
It can be argued that the last line serves readability purposes, just make more obvious that *head gets updated, though much less obviously that it is updated to NULL. The readability would better be served by the last line being (unneeded and) and setting to NULL explicitly.

Upvotes: 0

Alex
Alex

Reputation: 357

Since you expect to delete the whole list, then *head should be a null pointer after the execution of the final_delete() function. Then you could just omit the *head = tmp; line and just add a line after the while loop with *head = NULL;. To answer your question, the last line is redundant.

Upvotes: 1

Related Questions