访问动态分配列表中的元素

Accessing element in a dynamic-allocated list

本文关键字:元素 列表 动态分配 访问      更新时间:2023-10-16

所以我有这段代码重新创建了一个没有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;}

在此代码段中:

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分配内存,就会覆盖该指针并泄漏内存。插入的逻辑也存在问题。

以下代码片段插入到与哈希值对应的链表中,并且仅在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;
}

这是一个演示。如果我正确理解问题,它应该有效。至少它不再出现段错误。