gpt4 book ai didi

c - 在 C 中递归地从链表中删除元素

转载 作者:太空宇宙 更新时间:2023-11-04 04:24:48 28 4
gpt4 key购买 nike

我目前正在通过做老师发布给我们学习的练习题来备考,我正在努力从链表中递归删除元素。我得到一个无限循环,我不太清楚为什么!有人可以提示我正确的方向吗?我已经制作了一种无需递归即可删除元素的方法(在下面发布)并尝试遵循该指南。但是,我似乎无法让我的递归方法起作用。下面是我的代码:

void destroyListRecursive(node *head)
{
if ( head == NULL)
return;

destroyListRecursive(head->next);

free(head);
}

这是我的非递归函数(我查看了其他文章以获得指导,因为我遇到了一些问题,如果有问题请告诉我):

void destroyList (struct node** head)
{
struct node* current = *head;
struct node* next;

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

*head = NULL;
}

这是我的列表结构:

typedef struct node
{
// data field
int data;

// the next node in the list
struct node *next;
} node;

我真的很感激在正确的方向轻推! :)

最佳答案

您的代码取消引用链表最后一个元素上的 NULL 指针

if ( head->next == NULL)
return;

当最后一个元素递归传递给函数时,它的值将在 head 参数中,所以

if ( (NULL)->next == NULL)
return;

Undefined Behavior

你的递归函数必须只检查 head 值:

void destroyListRecursive(node *head)
{
if ( head == NULL)
return;

destroyListRecursive(head->next);

free(head);
}

关于c - 在 C 中递归地从链表中删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42758041/

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