【发布时间】:2014-09-06 23:38:12
【问题描述】:
我正在实现一个哈希表作为练习,需要创建一些函数,当负载超过 1.5 时,或者当哈希表中的条目数/桶数超过 1.5 时,该函数将扩大哈希图
我找到了哈希表的另一个实现。但是,不同之处在于我使用的存储桶指向单元格(在运行时动态创建),这些单元格都作为链表相互链接。该实现使用带有预分配结构的哈希表。
所以看起来有点像 [bucket] --> [cell of memory] --> [cell of memory] --> [cell of memory]
这是找到的实现:
static void expandIfNecessary(Hashmap* map) {
// If the load factor exceeds 0.75...
if (map->size > (map->bucketCount * 3 / 4)) {
// Start off with a 0.33 load factor.
size_t newBucketCount = map->bucketCount << 1;
Entry** newBuckets = calloc(newBucketCount, sizeof(Entry*));
if (newBuckets == NULL) {
// Abort expansion.
return;
}
// Move over existing entries.
size_t i;
for (i = 0; i < map->bucketCount; i++) {
Entry* entry = map->buckets[i];
while (entry != NULL) {
Entry* next = entry->next;
size_t index = calculateIndex(newBucketCount, entry->hash);
entry->next = newBuckets[index];
newBuckets[index] = entry;
entry = next;
}
}
// Copy over internals.
free(map->buckets);
map->buckets = newBuckets;
map->bucketCount = newBucketCount;
}
}
大部分都适用,除了这部分:
while (entry != NULL) {
Entry* next = entry->next;
size_t index = calculateIndex(newBucketCount, entry->hash);
entry->next = newBuckets[index];
newBuckets[index] = entry;
entry = next;
}
大概,我想确保链表被分开,以便条目仍然正确连接。我对确切理解这里发生的事情也有点模糊。
我的尝试如下:
while (entry != NULL) {
// use the pointer of this cell to get to the next cell, store this in a pointer called next
// hash the key of the current entry
...
这是我开始不了解实现以及我不确定如何处理我的链接列表的部分。我该如何应用这个?你能解释一下如何适应它吗?
【问题讨论】:
-
请说明您需要澄清什么?哈希表的概念还是使用现有密钥的当前实现?
-
@YuryLapitsky 我需要知道如何将此实现应用于我的特定数据结构。