C Linked-list Destroy Function

爱⌒轻易说出口 提交于 2019-12-04 14:32:01
spt025
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;
    }
    else
    {
        struct node *iter = *n;
        struct node *prev = NULL;

        /* get last item and previous one */
        while (iter->next != NULL)
        {
            prev = iter;
            iter = iter->next;
        }

        prev->next = NULL;
        free(iter);

        /* repeat call */
        clear(n);
    }
}

Hope this may help you.

As I see the solution of spt025, my one seems to have a bit too much code. I am just a beginner as well ;)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!