C链表销毁功能

问题描述 投票:3回答:3

我正在尝试学习C,而且和很多人一样,我对指针有些困惑。无论如何,我创建了一个递归函数来销毁我的链表,但是正如我调试过的那样,当我从函数中返回时,列表的头部不是应该的空值,因此我猜想这是一些基本的误解指针。这是函数:

void destroy(struct node* n){
   if(!n) return;
   destroy(n->next);
   free(n);
   n = NULL; }

提前感谢。

c function linked-list
3个回答
8
投票
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;
}

尝试这样...。您可以根据需要更改名称。如果您仍然需要帮助,请告诉我。


2
投票

此函数结束时头部已释放,但不为null。 C语言中的所有内容均按值传递。因此,您将头部位置的副本传递给销毁。该内存已释放,但磁头未更改。

您可以这样写:

destroy(&head);

void destroy(struct node** n){
   if(!*n) return;
   destroy(&((*n)->next));
   free(*n);
   *n = NULL; 
}

1
投票

您必须使用指向列表的指针,并使用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);
}

希望这对您有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.