首页 > 解决方案 > 我想确保我的链表工作

问题描述

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

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
}

标签: cdata-structures

解决方案


您的代码可能存在其他显示的问题,但存在以下问题addnode

  1. addnode不设置列表头部(即houses[i].next)。
  2. 因此,新添加的节点永远不会连接到任何东西[并且是内存泄漏]。
  3. 忽略 [明显] 错字/语法错误:void addnode{int a}而不是void addnode(int a).
  4. on 循环tmp 丢弃指向列表尾部的指针。我们需要一个单独的变量(例如prev)。
  5. 请注意,这i全局的。没关系,但是如果i是 to 的参数,该函数会更干净addnode
  6. 不要转换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;
}

推荐阅读