I am trying to learn C, and as many people, I have been a little stuck with pointers. Anyways, I made a recursive function that destroys my linked list, but as I have debugged, when I am back from the function the head of the list is not null as it should be, so I'm guessing it's some basic misunderstanding with pointers. Here's the function:
void destroy(struct node *n) {
if (!n) return;
destroy(n->next);
free(n);
n = NULL;
}
void deleteList(struct node** head_ref)
{
struct node* current = *head_ref;
struct node* next;
while (current != NULL) {
next = current->next;
free(current);
current = next;
}
*head_ref = NULL;
}
Try like this ....you can change names as you want. If you still need help let me know.
Head has been freed when this functions ends but it's not null. Everything in C is passed by value. So you pass a copy of the location of head into destroy. That memory is deallocated but head is not changed.
You could write this as:
destroy(&head);
void destroy(struct node** n){
if(!*n) return;
destroy(&((*n)->next));
free(*n);
*n = NULL;
}
You have to use a pointer pointing to your list, calling with destroy(&n)
:
// clear complete list
void destroy(struct node **n)
{
if (*n == NULL)
return;
if ((*n)->next == NULL)
{
free(*n);
*n= NULL;
return;
}
struct node *iter = *n;
struct node *prev = NULL;
// get last item and the previous one
while (iter->next != NULL)
{
prev = iter;
iter = iter -> next;
}
prev->next = NULL;
free(iter);
destroy(n);
}
Hope this may help you.
Your recursive destroy
function cannot modify the head
variable in the caller's frame.
The statement n = NULL
only affects the function argument, which is a local variable of the destroy
function. It actually has no effect, so you can remove this statement.
You should set the head
to NULL
after the call to destroy
in the caller function if it is needed there.
Here is the sample function to destroy Linked list using DeleteRear()
:
void Destroy_Using_Rear(List *L)
{
int y;
Node *P,*Q,*Z;
while(P!=NULL){
y=DeleteRear(L,x);
return y;
Z=P;
P=*L;
}
}