gpt4 book ai didi

C:如何释放链表中的节点?

转载 作者:太空狗 更新时间:2023-10-29 16:25:31 24 4
gpt4 key购买 nike

如何释放在另一个函数中分配的节点?

struct node {
int data;
struct node* next;
};

struct node* buildList()
{
struct node* head = NULL;
struct node* second = NULL;
struct node* third = NULL;

head = malloc(sizeof(struct node));
second = malloc(sizeof(struct node));
third = malloc(sizeof(struct node));

head->data = 1;
head->next = second;

second->data = 2;
second->next = third;

third->data = 3;
third->next = NULL;

return head;
}

我在main()中调用buildList函数

int main()
{
struct node* h = buildList();
printf("The second element is %d\n", h->next->data);
return 0;
}

我想释放头,第二个和第三个变量。
谢谢。

更新:

int main()
{
struct node* h = buildList();
printf("The element is %d\n", h->next->data); //prints 2
//free(h->next->next);
//free(h->next);
free(h);

// struct node* h1 = buildList();
printf("The element is %d\n", h->next->data); //print 2 ?? why?
return 0;
}

两个打印 2. 不应该调用 free(h) 删除 h。如果是这样,为什么 h->next->data 可用,如果 h 是免费的。当然,“第二个”节点没有被释放。但是由于 head 被移除,它应该能够引用下一个元素。这里有什么错误?

最佳答案

释放列表的迭代函数:

void freeList(struct node* head)
{
struct node* tmp;

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

}

函数的作用如下:

  1. 检查 head 是否为 NULL,如果是,则列表为空,我们直接返回

  2. head 保存在 tmp 变量中,并使 head 指向列表中的下一个节点(已完成在 head = head->next

  3. 现在我们可以安全地free(tmp) 变量,而head 只是指向列表的其余部分,回到步骤1

关于C:如何释放链表中的节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6417158/

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