I’m working through some pointer/linked-list problems. One of the problems is to delete all nodes in a list and point the head to NULL.
My solution differs from the given answer. I’m new to this, so I’m having trouble figuring out if and why mine doesn’t work. The main problem I’m having is trying to understand what the result of free(*headRef); is, and if *headRef can share a different pointee after that.
My thinking is: because I have compliment point to the next node, I can free *headRef which is pointing at the first node (or, more generally, the node before the one compliment is pointing to). Then, I can point *headRef to compliment and the process can continue.
Here’s my code:
void DeleteList(struct node** headRef){
struct node* compliment = *headRef;
while (compliment != NULL){
compliment = compliment->next;
free(*headRef);
*headRef = compliment;
}
*headRef = NULL;
}
Assume each node carries two attributes: an int and a ->next pointer.
The code that you’ve posted is fine. The key step in deleting all nodes is to make sure that you don’t try deleting a pointer and then following its
nextpointer. Since you use thecomplimentpointer to hold the next node on each iteration, what you have looks fine.As for
free(*headRef)– this deallocates the pointer pointed at byheadRef. Once you’ve done this, you should be sure not to follow the pointer*headRefanymore. Since you immediately change*headRefin the next line to point to the next node in the linked list, you don’t have anything to worry about. The main concern is not tofreea pointer and then try dereferencing it.freeing a pointer doesn’t somehow “poison” the pointer variable and make it bad; instead it destoys the pointee and makes that bad.One detail – the very last line of your function isn’t necessary, since when you visit the last node of the linked list and traverse its
nextpointer, you will getNULL. This means that the final iteration of the loop will set*headRefto point toNULLfor you.Hope this helps!