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

时间:2018-04-22 00:12:50

标签: c++ pointers hashtable traversal

我正在编写链式哈希表代码。 我不明白为什么当我插入后设置NULL时,我的链表遍历不会停留在entry->next->next = 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();


}

1 个答案:

答案 0 :(得分:0)

下面:

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

你看到了问题吗?