在哈希表中查找最长的碰撞(链)

时间:2015-03-22 21:58:42

标签: c++ hashtable collision

我需要查找并输出插入哈希表时发生的最长冲突。我知道我必须记录所有碰撞计数并找出哪一个是最大的,但我仍然坚持弄清楚如何。

这是我的代码:

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;
}

};

是否有一种简单的方法可以在&#34;插入&#34;? 任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

您可以创建整数变量maxChainmaxChainIndex,分别跟踪最长链及其索引。 你的插入函数就像:

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;
}