【发布时间】: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