Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Linked-list Destroy Function

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;
}
like image 354
C. Porto Avatar asked Sep 01 '25 17:09

C. Porto


1 Answers

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.

like image 70
spt025 Avatar answered Sep 04 '25 11:09

spt025