c - 如何删除整个列表,而不仅仅是删除列表中的元素?
问题描述
这是我必须在列表中创建列表和元素的代码。现在我想实现一个函数来删除整个列表,而不仅仅是清空列表。我怎么做?
struct node
{
int number;
struct node* next;
};
struct forward_list
{
struct node* head;
};
typedef struct node node;
node* create_node(int number, node* next)
{
node* result = (node*)malloc(sizeof(node));
result->number = number;
result->next = next;
return result;
}
//edit
void destroy_node(node* const this)
{
free(this);
}
void destroy_list(forward_list* const this)
{
/* TODO */
}
解决方案
看到你的编辑,我认为你只需要destroy_node
迭代地调用destroy_list
来清空你的列表,从而破坏它。
[编辑]
我不得不将列表的头部设置NULL
在最后。感谢您的评论!
像这样的东西:
void destroy_list(forward_list* const this)
{
node* temp = this->head;
node* to_delete;
while(temp != NULL){
to_delete = temp;
temp = temp->next;
destroy_node(to_delete);
}
this->head = NULL;
}
推荐阅读
- html - 使用缩放参数嵌入 Google drive PDF
- arrays - Bulls and cows - c语言 - 比较数组
- apache-camel - Camel 事务处理的 JMS 组件不适用于聚合器
- ios - 在 UITextView 中点击 URL 时 iOS 应用程序崩溃
- session - 如何在 MobaXterm 中全局启用会话日志记录?
- jsp - 影响应用程序内部流程的 beforeunload 事件
- oracle - 无法创建包含枚举字段的表(Oracle 11g)
- c++ - BOOST_BUILD_PATH 目录
- java - 使用休眠搜索在 json 字段中搜索
- amazon-web-services - ECS 上下文中的 Docker 撰写作业无法获取 AWS 机密以从 DockerHub 检索图像