c - 我想确保我的链表工作
问题描述
这是做链表的正确方法吗?我在一个大型学校项目中遇到问题,现在我想确保这是真的。
void addnode(int a){
struct house* tmp = houses[i].next;
while (tmp != NULL) {
tmp = tmp->next;
}
tmp = (struct house*)malloc(sizeof(struct house));
tmp->id=a;
tmp->next=NULL;
}
我发现错误可能出现在代码的其他部分。现在我将分享我怀疑我希望你能帮助我的部分。house[i] 是一个链表数组。如果 house[i].id==-1 它是空的
struct house get_house_byid(int id) {
for (int i = 0; i < 1000; i++) {
if (houses[i].id != -1) {
if (houses[i].id == id) {
return houses[i];
}
if (houses[i].next != NULL) {
struct house* tmp = houses[i].next;
while (tmp != NULL) {
if (tmp->id == id) {
return *tmp;
}
tmp = tmp->next;
}
}
}
}
struct house housep;
housep.id = -1;
return housep;//if it cant find that id it returns housep
}
解决方案
您的代码可能存在其他未显示的问题,但存在以下问题addnode
:
addnode
不设置列表的头部(即houses[i].next
)。- 因此,新添加的节点永远不会连接到任何东西[并且是内存泄漏]。
- 忽略 [明显] 错字/语法错误:
void addnode{int a}
而不是void addnode(int a)
. - on 循环
tmp
丢弃指向列表尾部的指针。我们需要一个单独的变量(例如prev
)。 - 请注意,这
i
是全局的。没关系,但是如果i
是 to 的参数,该函数会更干净addnode
。 - 不要转换
malloc
:我是否转换了 malloc 的结果?
这是一些重构的代码。注释如下:
void
addnode(int i,int a)
{
struct house *tmp;
struct house *prev;
// find the tail of the list
prev = NULL;
for (tmp = houses[i].next; tmp != NULL; tmp = tmp->next)
prev = tmp;
// allocate the new node
tmp = malloc(sizeof(*tmp));
tmp->id = a;
tmp->next = NULL;
// append to the tail of the [non-empty] list
if (prev != NULL)
prev->next = tmp;
// add to front of the empty list
else
houses[i].next = tmp;
}
推荐阅读
- spring - Zuul 和 Eureka 设置行为怪异
- java - 为什么 ForkJoinPool 使用 ThreadPerTaskExecutor?
- android - 排序在我的应用程序的领域数据库中不起作用
- c# - or-tools:将 BoundIntegerExpression 转换为 IntegerExpression
- node.js - 在选项卡处于非活动状态时保持 Socket.io 活动
- javascript - 如何在输入文本字段中只允许字符串
- javascript - 在编辑文本旁边显示弹出框
- php - SQLSTATE[HY000]:[Microsoft][ODBC Driver 11 for SQL Server]TDS 协议错误
- cakephp-3.7 - 如何在 CakePHP 3.7 中创建查询构建器失败
- excel - 通过vba下拉列表