gpt4 book ai didi

c - 删除链表时输出错误

转载 作者:太空宇宙 更新时间:2023-11-04 02:57:42 27 4
gpt4 key购买 nike

ccarrill@ubuntu:~/C$ ./ccarri7lab9
q: quit the program
i: inserts an integer value
d: deletes an integer value
c: checks if an integer value is in the list
e: deletes all integers from the list
l: lists the items in the list (small to big)
r: lists the items in reverse order (big to small)

Please make a choice: i
Enter the value you want to insert: 3
Please make another choice: i
Enter the value you want to insert: 4
Please make another choice: i
Enter the value you want to insert: 5
Please make another choice: l //lists integers
3 4 5
Please make another choice: e //deletes list
Please make another choice: l //lists integers
137904144 137904160 0 // output
Please make another choice: q

除了我的删除列表功能外,一切正常。出于某种原因,它在应该释放每个节点(从而释放整个链表)时输出垃圾。每个函数都必须递归完成(这是一个赋值)。

void deleteList(node* head)
{
if(head)
{
deleteList(head->next);
free(head);
}
}

最佳答案

删除整个列表后,需要将head 指针设置为NULL。否则它会悬空,导致 undefined behaviour当您尝试打印列表时。

为了能够在 deleteList() 中执行此操作,您需要更改函数以将 head 作为双指针(node** )。

关于c - 删除链表时输出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15493468/

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