C 我想确保我的链表工作正常

C 我想确保我的链表工作正常,c,data-structures,C,Data Structures,这是制作链表的正确方法吗?我在学校的一个大项目中遇到了问题,现在我想确保这是真的 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->nex

这是制作链表的正确方法吗?我在学校的一个大项目中遇到了问题,现在我想确保这是真的

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;
}
我发现错误可能在代码的其他部分。现在我将分享我怀疑的部分,希望你能帮助我。 houses[i]是一组链表。如果为[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
}
struct house get\u house\u byid(int id){
对于(int i=0;i<1000;i++){
if(房屋[i].id!=-1){
if(房屋[i].id==id){
归还房屋[i];
}
if(houses[i].next!=NULL){
struct house*tmp=houses[i]。下一步;
while(tmp!=NULL){
如果(tmp->id==id){
返回*tmp;
}
tmp=tmp->next;
}
}
}
}
结构住宅;
housepid=-1;
return housep;//如果找不到该id,则返回housep
}
您的代码可能存在其他未显示的问题,但是
addnode
存在以下问题:

  • addnode
    不设置列表的标题(即
    包含[i].next
  • 因此,新添加的节点从未连接到任何东西[并且是内存泄漏]
  • 忽略[明显]键入/语法错误:
    void addnode{int a}
    而不是
    void addnode(int a)
  • tmp
    上的循环丢弃指向列表尾部的指针。我们需要一个单独的变量(例如
    prev
  • 请注意,
    i
    是全局的。这很好,但是如果将
    i
    作为
    addnode
    的参数,则函数会更简洁
  • 不要强制执行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;
    }
    

    您的代码看起来可以满足您的要求。您是否测试过它以确保它工作正常?你说的“正确的方法”是什么意思?有一种方法可以用递归来写这个;它和你的方式一样“正确”,但它不起作用,因为它只是更大代码的一小部分,任何其他部分都可能被破坏。你救了我的一天,你是英雄,不客气。第一个链表实现的问题在这里是一个非常常见的问题,所以你并不孤单。快乐编程!