删除整个链表

时间:2013-10-19 21:41:02

标签: c list pointers memory linked-list

我正在使用链接列表并填充结构但是当我删除整个结构并尝试打印链表的内容(应该为空)时,会出现一个数字列表。我知道这可能是一个记忆问题。有关如何修复它的任何建议吗?

删除整个链表的代码:

void destroy(set_elem *head)
{
    set_elem *current = head;
    set_elem *next;

    while (current != NULL)
    {
       next = current->next;
       free(current);
       current = next;
    }
    head = NULL;
}

4 个答案:

答案 0 :(得分:2)

当您的 delete 功能正常工作时,当您执行head = NULL;时,它不会将调用者中的 head 设置为NULL,因为您只修改了本地指针,通过检查head的值,导致您在以后的逻辑中尝试打印值。

要修改原始指针,请将指针传递给head并设置*head=NULL;

void destroy(set_elem **head)
{
set_elem *current = *head;

/* rest is the same */

*head = NULL;
}

答案 1 :(得分:1)

复制传入函数的头指针时,头节点不受影响。您必须将引用传递给指向头部的指针,然后您才能删除头指针。这也可以通过将指针传递给指向链表头部的指针来完成,但我发现传递引用更方便。以下是对您的代码的更改。

void destroy(set_elem*& head)
{

  set_elem* current = head;
  set_elem* next;

  while (current != NULL)
  {
       next = current->next;
       free(current);
       current = next;
  }

   *head = NULL;
}

答案 2 :(得分:1)

你没有改变原来的头脑。您应该将指针传递给此头部,即指向指针的指针,或者应该将更改的头部返回给调用者。以下是将更改的头返回给调用者的代码。还有其他答案显示指向指针的指针。

  set_elem* destroy(set_elem *head) {
      set_elem *current = head;
     set_elem *next;

     while (current != NULL) {
         next = current->next;
         free(current);
         current = next;
     }
     head = NULL;
     return head;
   }

在来电者中,

    head = destroy(head);

答案 3 :(得分:0)

您只修改本地head指针

使用双指针修改head,稍后将用于打印/处理

void destroy(set_elem** head)
{

   set_elem* current = *head;
   set_elem* next;

   while (current != NULL)
   {
       next = current->next;
       free(current);
       current = next;
   }

   *head = NULL;
}
相关问题