【发布时间】:2017-07-24 22:37:07
【问题描述】:
我正在学习哈希表,并在另一个网站上找到了此代码,但无法理解 Insert(int key, int value) 函数。 该功能运行良好,但我想知道是否有不需要的额外代码,或者我是否不完全理解它。
具体来说,函数末尾的else条件:
else
{
entry->value = value;
}
当我使用不同的参数调用该函数时,它似乎永远不会达到那个条件。这是其余的代码。
#include<iostream>
#include<cstdlib>
#include<string>
#include<cstdio>
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;
}
};
class HashMap
{
private:
HashNode** htable;
public:
HashMap()
{
htable = new HashNode*[TABLE_SIZE];
for (int i = 0; i < TABLE_SIZE; i++)
htable[i] = NULL;
}
~HashMap()
{
for (int i = 0; i < TABLE_SIZE; ++i)
{
HashNode* entry = htable[i];
while (entry != NULL)
{
HashNode* prev = entry;
entry = entry->next;
delete prev;
}
}
delete[] htable;
}
/*
* Hash Function
*/
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;
}
}
else
{
entry->value = value;
}
}
/* Search Element at a key
*/
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.Search(3);
}
高度赞赏任何澄清。
谢谢
【问题讨论】:
-
首先要做的是整理缩进。糟糕的缩进让代码更难解释。
-
现在不碍事了,让我们来看看......
-
这只是一段多余的代码。正如您所观察到的,由于循环,条目保证为空。如果 hash 和 key 都匹配,你确实设置了 value,但这在其他地方处理。