如何访问链式哈希表链表中的每个节点

How to Visit Each Node in Chained Hash Table Linked Lists

本文关键字:链表 节点 哈希表 何访问 访问      更新时间:2023-10-16

我正在编写链式哈希表代码。我不明白为什么我的链表遍历在插入后设置entry->next->next = NULL时没有停止在NULL。我省略了对我的问题没有用的代码:是什么导致"printTable"中的链表遍历永远循环?

ChainHash.h:

class Entry {
private:
    string key;
    int value;
    Entry *next;
    friend class HashTable_CH;
public:
    Entry(string k, int v) {
            key = k;
            value = v;
            next = NULL;
    }
};

class HashTable_CH {
private:
    Entry **slots;
    const int DEFAULT_CAP = 11;
    const float load_factor = 0.5;
    int capacity;
    int size;
    //int isPrime(int n) {
    //int calculateGrowSize() {
    int hash(string k) {
            int c = 0;
            for (int i = 0; i < k.length(); i++)
                    c += int(k[i]);
            return c % capacity;
            }
    //int probe(int hash, int index) {
public:
    HashTable_CH() {
            slots = new Entry*[DEFAULT_CAP];
            capacity = DEFAULT_CAP;
            size = 0;
            for (int i = 0; i < DEFAULT_CAP; i++)
                    slots[i] = NULL;
    }
    void Insert(string key, int value) {
            if (float(size) / float(capacity) >= load_factor)
                    //grow();
                    return;
            int h = hash(key);
            if (slots[h] == NULL) {
                    slots[h] = new Entry(key, value);
                    size++;
                    return;
            } else {
                    Entry *entry = slots[h];
                    while (entry->next != NULL)
                            entry = entry->next;
                    entry->next = new Entry(key, value);
                    entry->next->next = NULL;
            }
    }

    //bool Search(string, int &value) {             
    //void Remove(string key) {             
    void printTable() {
            for (int i = 0; i < capacity; i++) {
                    cout << "Slot " << i << ": ";
                    if (slots[i] == NULL)
                            cout << "*****";
                    else {
                            Entry **temp = slots;
                            while (temp != NULL) {
                                    cout << "Key: " << slots[i]->key << ", " << slots[i]->value;
                            }
                            }
                    } cout << "n";
            } cout << "n";
    }
};

testChainedHash.cpp:

#include"ChainHash.h"
int main() {
    HashTable_CH t1;
    t1.Insert("froyo", 500);
    t1.Insert("froyo", 600);
    t1.Insert("froyo", 700);

    t1.printTable();

}

在这里:

while (temp != NULL) {
  cout << "Key: " << slots[i]->key << ", " << slots[i]->value;
}

你看到问题了吗?