【发布时间】:2021-05-25 14:56:17
【问题描述】:
这是做链表的正确方法吗?我在一个大型学校项目中遇到了问题,现在我想确保这是真的。
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] 是一个链表数组。如果houses[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
}
【问题讨论】:
-
你的代码看起来会做你想做的事。您是否对其进行了测试以确保其有效? “正确的方式”是什么意思?有一种方法可以使用递归来编写它;它和你的方式一样“正确”。
-
但它不起作用
-
因为它只是较大代码的一小部分,任何其他部分都可以被破坏
标签: c data-structures