gpt4 book ai didi

c++ - 哈希表 - 链表数组 - C++

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:20:57 26 4
gpt4 key购买 nike

我正在尝试通过在链接节点上使用数组(创建链接列表)来创建哈希表。但是我在向哈希表中插入一个值时遇到了困难。当我运行它时,我得到这个:

http://gyazo.com/3a28a70e66b3ea34e08223e5948f49c0.png

这是我的代码:

#include <iostream>
using namespace std;

class Node {
public:
int num;
Node * next;
};

class intHashTable {
private:
int size;
Node ** table;
public:
intHashTable(int size); // construct a new hash table with size elements
~intHashTable(); // delete the memory for all internal components
void insert(int num); // insert num into the hash table, no effect
// if num is already in table
void remove(int num); // remove num from the hash table, no effect if not in table
int lookup(int num); // return 1 if num is already in table, 0 otherwise
void print(void); // print the elements of the hash table to the screen
};

// construct a new hash table with nelements elements
intHashTable::intHashTable(int nelements)
{
size = nelements;
table = new Node*[size];
for ( int i = 0; i < size; i++ ) {
table[i] = NULL;
}
}

intHashTable::~intHashTable()
{
for(int i=0; i<size; i++)
{
Node* temp = table[i];
while(temp != NULL)
{
Node* next = temp->next;
delete temp;
temp = next;
}
}
size = 0;
delete[] table;
}

void intHashTable::insert(int num){
int location = ((unsigned)num) % size;
Node *runner = table[location];
if(runner == NULL ){
runner->num = num;
}else{
while(runner != NULL ){
runner = runner->next;
}
runner->num = num;
}
}

int main(){
intHashTable a (10);
a.insert(2);
return 0;
}

最佳答案

intHashTable构造完成后,table的所有元素仍然是NULL。但是,在函数 insert 中,一个元素被解除引用:

Node *runner = table[location];
runner = runner->next;

这会使程序崩溃,因为it is illegal to dereference a null pointer .

关于c++ - 哈希表 - 链表数组 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14457910/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com