【发布时间】:2017-07-25 18:55:25
【问题描述】:
这是对我提出的另一个问题的跟进,它是关于 this->next = NULL 指针在下面的 HashNode 构造函数中。 我的问题是,我不明白为什么 htable[hash_val]->next 不等于 NULL 而是实际上有一个内存地址,即使 this->next = NULL ,如构造函数中所写。
谁能告诉我为什么 htable[hash_val]->next 不等于 NULL 并且有一个与之关联的地址。找了一会儿好像没找到。我可以看到 htable[hash_val] 会有一个值,但我认为 htable[hash_val]->next 会是 NULL 。谢谢 。
#include<iostream>
using namespace std;
const int TABLE_SIZE = 128;
class HashNode
{
public:
int key;
int value;
HashNode* next;
HashNode(int key, int value)
{
this->key = key;
this->value = value;
this->next = NULL; // shouldn't htable[hash_val]->next = NULL
}
};
class HashMap
{
private:
HashNode** htable;
public:
HashMap()
{
htable = new HashNode*[TABLE_SIZE];
for (int i = 0; i < TABLE_SIZE; i++)
htable[i] = NULL;
}
int HashFunc(int key)
{
return key % TABLE_SIZE;
}
/*
* Insert Element at a key
*/
void Insert(int key, int value)
{
int hash_val = HashFunc(key);
HashNode* prev = NULL;
HashNode* entry = htable[hash_val];
while (entry != NULL)
{
prev = entry;
entry = entry->next;
}
if (entry == NULL)
{
entry = new HashNode(key, value);
if (prev == NULL)
{
htable[hash_val] = entry;
}
else
{
prev->next = entry;
}
}
}
void testnull(int key){
int hash_val = HashFunc(key);
cout<<htable[hash_val]->next; // outputs an address , not NULL
}
int Search(int key)
{
bool flag = false;
int hash_val = HashFunc(key);
HashNode* entry = htable[hash_val];
while (entry != NULL)
{
if (entry->key == key)
{
cout<<entry->value<<" ";
flag = true;
}
entry = entry->next;
}
if (!flag)
return -1;
}
};
int main() {
HashMap hash;
hash.Insert(3,7);
hash.Insert(3,8);
hash.testnull(3);
// your code goes here
return 0;
}
【问题讨论】:
标签: c++ pointers this hashtable