我尝试使用线性探测冲突解决方法为哈希表编写正确的删除函数。
我运行一个测试程序,从哈希表中删除几条记录。在某些时候,我的find函数找不到要删除的元素。但是,它应该还在桌子上。我认为我正在以错误的方式在remove()中进行rehash。
类HashTable
包含成员table
,类型为Record
template <class TYPE>
struct Record{
string key;
TYPE value = NULL;
Record(){
key = "";
value = 0;
}
Record(const char* key_, TYPE value_){
key = key_;
value = value_;
}
Record(string key_, TYPE value_){
key = key_;
value = value_;
}
};
template <class TYPE>
bool HashTable<TYPE>::remove(const char* key){
int tvalue; //temporary unused value to make find work
if (find(key, tvalue))
{
table[lastFoundIdx].key = ""; //lastFoundIdx - index of element that contains a key
table[lastFoundIdx].value = 0;
numRec--; //reduce number of records in table
int startIdx = lastFoundIdx; //rehash will stat form start Index
int i;
if (lastFoundIdx == maxSize - 1)
i = 0;
else
i = lastFoundIdx + 1;
while (table[i].key != ""&&i != maxSize){ // rehash starts here
std::size_t h1 = std::hash<std::string>()(table[i].key);
int hash = h1%maxSize;
if (hash < i&&hash >= startIdx){
table[startIdx].key = table[i].key;
table[startIdx].value = table[i].value;
table[i].key = "";
table[i].value = 0;
startIdx = i;
}
i++;
}
return true;
}
else return false;
}
这里也是我的查找功能,似乎工作正常,但我可能是错的
template <class TYPE>
bool HashTable<TYPE>::find(const char* key, TYPE& value){
std::size_t h1 = std::hash<std::string>()(key);
int hash = h1%maxSize;
int startIdx = hash;
while (table[hash].key != "" && table[hash].key != key){
hash = (hash + 1) % maxSize;
if (hash == startIdx)
return false;
}
if (table[hash].key == "")
return false;
else{
lastFoundIdx = hash;
value = table[hash].value;
return true;
}
}
请您帮我确定我是否正确地进行线性探测?