【问题标题】:Is this a proper implementation of a DeleteList function? [LINKED LIST via heaps]这是 DeleteList 函数的正确实现吗? [通过堆的链接列表]
【发布时间】:2018-08-17 17:01:56
【问题描述】:

我必须编写一个函数 DeleteList(),它接受一个列表,释放其所有内存并将其头指针设置为 NULL(空列表)。

它似乎有效,但如果它真的有效,因为我实施的方式(我认为是错误的方式)与解决方案中的方式截然不同。我认为它只删除了几个节点,或者内存管理存在问题。

int Length(struct node* head)
{
    int count = 0;
    struct node* current = head;
    while (current != NULL)
    {
        count++;
        current = current->next;
    }
    return(count);
}

void DeleteList(struct node** headRef)
{
    int len = Length(*headRef);
    for(int i = 0;i<len;i++)
        free(*headRef);
    *headRef = NULL;
}

【问题讨论】:

  • 不,不是。你释放了相同的指针Len 次。
  • 我就是这么想的——我太傻了。我觉得我正在这样做。

标签: c data-structures linked-list


【解决方案1】:

您实际上并没有释放整个链表,而是反复释放头节点。我建议您使用以下方法。

void DeleteList(struct node** headRef) { 
    struct node *ptr = *headRef;
    struct node *temp = NULL;

    while(ptr)
    {
          temp = ptr;
          ptr = ptr->next;
          free(temp);
    }

    *headRef = NULL;
    }

【讨论】:

  • 是的,添加了@FiddlingBits
猜你喜欢
  • 2015-06-02
  • 1970-01-01
  • 1970-01-01
  • 2011-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-11
相关资源
最近更新 更多