C Linked-list Destroy Function

心已入冬 提交于 2019-12-06 08:17:22

问题


I'm trying to learn C, and as many people, I've been a little stuck with pointers. Anyways, I made a recursive function that destroys my linkedlist, but as I've debugged, when I'm 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; }

Thanks in advance.


回答1:


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.




回答2:


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; 
}



回答3:


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 ;)



来源:https://stackoverflow.com/questions/18412620/c-linked-list-destroy-function

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