【问题标题】:Accessing element in a dynamic-allocated list访问动态分配列表中的元素
【发布时间】:2020-10-24 14:44:53
【问题描述】:

所以我有这段代码重新创建一个没有 STL 的单独链接的哈希表(我的任务禁止它)。不幸的是,我无法修改使用的任何结构。 TElem 是 int 值,NULL_TELEM 是识别空元素的值,elem 是值。

如果我尝试添加更多具有相同 hashValue 的数字,例如 7777 和 8777,如果哈希函数返回数字的 %100(标有注释的 while 是无法正确访问内存的位置),则会出现问题:

我怎样才能让它工作?

(已更新)

为方便起见,我将添加一个可复制粘贴的代码,包括以前的功能(全部在一个文件中):

#include<iostream>
#include<assert.h>

typedef int TElem;

#define NULL_TELEM -111111

int hashFunction(TElem elem){

     return elem%100; //key: 1905, it returns 5
};

struct Node
        {
            TElem val=NULL_TELEM;
            Node* next;
    };

class Book {
private:
       unsigned int m;
       Node* nodes;

    public:
        Book() {
    m = 0;
    this->nodes = new Node[100];
    for(int i=0; i<100; i++)
    {
        nodes[i].val=NULL_TELEM;
        nodes[i].next=nullptr;
    }
};
        bool add(TElem elem){
    if(elem<1000 || elem>9999)
        return false;
    int hashValue = hashFunction(elem);
    if(nodes[hashValue].val==elem)
        return false;
    if(nodes[hashValue].next==nullptr && nodes[hashValue].val==NULL_TELEM)
    {
        nodes[hashValue].val = elem;
        m++;
        return true;
    }
    Node* b1=new Node;
    b1=nodes[hashValue].next;
    while (b1->val != elem && b1->val != NULL_TELEM)   //Here?? Exactly at this while
        b1=b1->next;
    if (b1->val != elem)
    {
        b1->next->val = elem;
        b1->next->next = nullptr;
        m++;
        return true;
    }
    return false;
};
};

int main()
{ Book b;
assert(b.add(7777)==true);
assert(b.add(8777)==true); //this is where it doesn't work
return 0;}

【问题讨论】:

  • while出现什么问题?是什么让您认为该程序不起作用?
  • 似乎无法访问内存。当我尝试添加多个具有相同哈希值的数字时它不起作用(我通过测试所有可能的情况得出结论)
  • 那么请用失败的案例更新问题。我们需要能够重现错误以提供帮助。
  • 更新了!给您带来的不便深表歉意!
  • 这仍然不是minimal reproducible example。我们应该能够复制粘贴您的代码,然后查看错误。

标签: c++ memory-management dynamic linked-list


【解决方案1】:

在这个sn-p中:

Node* b1=new Node;
b1=nodes[hashValue].next;
while (b1->val != elem && b1->val != NULL_TELEM)   //Here?? Exactly at this while
    b1=b1->next;
if (b1->val != elem)
{
    b1->next->val = elem;
    b1->next->next = nullptr;
    m++;
    return true;
}

添加到特定链接列表的位置有几个问题。一旦为b1 分配内存,就会覆盖该指针并泄漏内存。插入的逻辑也有问题。

下面的sn-p插入到哈希值对应的链表中,只有elem不存在时才插入。我删除了对 NULL_ELEM 的检查,因为这似乎是多余的。

auto b1 = nodes + hashValue;
while (b1->next && b1->val != elem)  // the check for next is very important
    b1=b1->next;
if (b1->val != elem)    
{ 
    b1->next = new Node{elem, nullptr};
    m++;
    return true;
}

这是demo。如果我正确理解问题,它应该可以工作。至少它不再出现段错误。

【讨论】:

  • 你真的是个英雄!!!感谢您所做的一切(尤其是您的耐心)!!!
  • @Kreatives 没问题,很乐意提供帮助 :) 将来,请尝试遵循我在发布问题时给出的建议,您会更快地获得帮助。另外,如果答案解决了您的问题,请考虑接受它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-29
  • 2022-11-13
  • 1970-01-01
  • 2021-02-20
  • 2011-12-10
  • 2021-06-29
相关资源
最近更新 更多