【问题标题】:i want to make sure that my linked list work我想确保我的链表工作
【发布时间】: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


【解决方案1】:

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

  1. addnode设置列表的头部(即houses[i].next)。
  2. 因此,新添加的节点从未连接到任何东西[并且是内存泄漏]。
  3. 忽略 [明显] 错字/语法错误:void addnode{int a} 而不是 void addnode(int a)
  4. tmp 上的循环丢弃指向列表尾部的指针。我们需要一个单独的变量(例如prev)。
  5. 请注意,i全局。这很好,但如果 iaddnode 的参数,函数会更简洁。
  6. 不要投malloc的返回:Do I cast the result of 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;
}

【讨论】:

  • 你拯救了我成为英雄的一天
  • 不客气。一个人的第一个链表实现的问题在 SO 上是一个非常常见的问题,所以你并不孤单。快乐编程!
猜你喜欢
  • 2017-07-26
  • 2021-05-18
  • 1970-01-01
  • 2018-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-11
相关资源
最近更新 更多