【发布时间】:2015-03-22 21:58:42
【问题描述】:
我需要找到并输出插入哈希表时发生的最长冲突。我知道我必须记录所有的碰撞计数并找出哪一个是最大的,但我一直在弄清楚如何做。
这是我的代码:
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;
}
};
在“插入”中有简单的方法吗? 任何帮助表示赞赏。
【问题讨论】:
-
你想为每个插入输出冲突计数(也就是那个索引有多少条目)?或者你想要一些函数来输出哈希表中最长的链?
-
我不想在索引处输出碰撞计数,我想输出最长的链,所以我需要创建一个输出函数。