正在哈希表中查找最长的冲突(链)
Finding the longest collision (chain) in hashtable
我需要找到并输出插入哈希表时发生的最长冲突。我知道我必须记录所有的碰撞次数,找出哪一次碰撞次数最大,但我一直在想办法。
这是我的代码:
class Entry {
private:
int key;
string value;
Entry *next;
public:
Entry(int key, string value) {
this->key = key;
this->value = value;
this->next = NULL;
}
int getKey() {
return key;
}
void setValue(string value) {
this->value = value;
}
Entry *getNext() {
return next;
}
void setNext(Entry *next) {
this->next = next;
}
};
const int TABLE_SIZE = 587;
class HashMap {
private:
Entry **table;
public:
HashMap() {
table = new Entry*[TABLE_SIZE];
for (int i = 0; i < TABLE_SIZE; i++)
table[i] = NULL;
}
void insert(int key, string value) {
int hash = (key % TABLE_SIZE);
if (table[hash] == NULL)
table[hash] = new Entry(key, value);
else {
Entry *entry = table[hash];
while (entry->getNext() != NULL)
entry = entry->getNext();
if (entry->getKey() == key)
entry->setValue(value);
else
entry->setNext(new Entry(key, value));
}
}
int sizeofTable()
{
return TABLE_SIZE;
}
~HashMap() {
for (int i = 0; i < TABLE_SIZE; i++)
if (table[i] != NULL) {
Entry *prevEntry = NULL;
Entry *entry = table[i];
while (entry != NULL) {
prevEntry = entry;
entry = entry->getNext();
delete prevEntry;
}
}
delete[] table;
}
};
在"插入"中有没有一种简单的方法可以做到这一点?感谢您的帮助。
您可以创建整数变量maxChain
和maxChainIndex
,它们分别跟踪最长的链及其索引。你的插入函数是这样的:
void insert(int key, string value) {
int hash = (key % TABLE_SIZE);
int chain = 1;
if (table[hash] == NULL)
table[hash] = new Entry(key, value);
else {
Entry *entry = table[hash];
while (entry->getNext() != NULL) {
++chain; //Count the entries as we're searching for the last one
entry = entry->getNext();
}
if (entry->getKey() == key)
entry->setValue(value);
else {
entry->setNext(new Entry(key, value));
++chain; //+1 for the newly inserted element.
}
}
if(chain > maxChain) {
maxChain = chain;
maxChainIndex = hash;
cout << "Current longest collision: " << maxChain << " at index: "
<< maxChainIndex << endl;
}
}
你可以制作一个函数来检索maxChain
,比如:
int getLongestChain() {
return maxChain;
}
相关文章:
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何将这个C++哈希表转换为动态扩展和收缩,而不是使用硬设置的最大值
- 用C++将哈希表写入文件并从文件中恢复
- C++中的并发哈希表
- 在具有开放寻址的哈希表中插入节点 [优化逻辑]
- 与C++哈希表的基础知识混淆
- 调整大小和复制哈希表数组中的元素
- 带链接的基本哈希表
- C++哈希表中,两个相同的实现,但一个给出错误
- 如果索引不是整数,我们如何在 C++ 中插入哈希表
- 查找项目在哈希表中的位置
- C++哈希表 - 如何解决自定义数据类型作为键的unordered_map冲突?
- 正在哈希表中查找最长的冲突(链)
- 哈希表中的冲突处理
- 用C++实现哈希表冲突的避免与解决
- 在c++中向哈希表中添加项会产生访问冲突异常
- 在c++中使用unordered_map实现哈希表并处理冲突
- c++哈希表和链表的访问冲突
- 哈希表冲突,如何获得正确的值
- 哈希表实现,集合的零冲突?发人深思的东西