如何访问链式哈希表链表中的每个节点
How to Visit Each Node in Chained Hash Table Linked Lists
我正在编写链式哈希表代码。我不明白为什么我的链表遍历在插入后设置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;
}
你看到问题了吗?
相关文章:
- 如何按数字顺序插入链表节点?
- 插入一个基本的单向链表节点似乎破坏了我的 c++ 代码?
- 在 c++ 中,在链表节点上使用括号有什么意义?
- C++链表节点是指它自己
- 不显示链表节点
- 如何取消引用作为指针的链表节点数据
- 删除链表节点,C++函数不起作用
- 基本C++链表节点和指针探针
- 链表节点上的分段错误
- 链表节点合并器函数
- 如何将链表节点中的值相加,C++
- 释放链表节点时出现分段错误
- 链表节点类中的链接数
- 链表 c++ 节点构造函数
- 当链表节点是用"new"构造时,如何删除列表?
- 双向链表节点的下一个是私有的
- 分段 C++中链表节点分配的错误
- 双向链表节点交换问题
- 在单向链表中添加双向链表节点
- 关于链表节点的说明