gpt4 book ai didi

c - 这是 DeleteList 函数的正确实现吗? [通过堆的链接列表]

转载 作者:太空宇宙 更新时间:2023-11-04 01:47:01 26 4
gpt4 key购买 nike

我必须编写一个函数 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;
}

最佳答案

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

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

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

*headRef = NULL;
}

关于c - 这是 DeleteList 函数的正确实现吗? [通过堆的链接列表],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51900015/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com