【发布时间】:2018-04-24 23:16:21
【问题描述】:
我正在尝试在 C 中创建一个 HashTable,其中每个“桶”都是指向 LinkedList 的指针。也就是说,我需要创建一个LinkedList 指针数组。
截至目前,SomeHashTable->Buckets[i] 正在返回一个非指针 LinkedList。我一直在到处寻找答案,但我什么也找不到。也许我忽略了什么?我在下面给出了我当前的代码。
HashTable.h
#include "LinkedList.h"
typedef struct HashTable
{
LinkedList* Buckets[1009];
} HashTable;
//Creates new hashtable
HashTable* HashTable_new();
//Hashes and adds a new entry
void HashTable_add(HashTable* Table, int data);
HashTable.c
#include "HashTable.h"
HashTable* HashTable_new()
{
HashTable* newTable = (HashTable*)malloc(sizeof(HashTable));
newTable->Buckets = malloc(1009 * sizeof(LinkedList*));
//Create linked lists
for (int i = 0; i < 1009; i++)
{
newTable->Buckets[i] = LinkedList_new();
}
return newTable;
}
void HashTable_add(HashTable* Table, int data)
{
int index = data % 1009;
//Get bucket to hash to
LinkedList* BucketHead = (Table->Buckets[index]);
//Hash it iiinnnn real good
LinkedList_add_at_end(BucketHead, data);
}
链表结构供参考:
typedef struct LinkedListNode {
int data;
struct LinkedListNode *next;
struct LinkedListNode *prev;
} LinkedListNode;
typedef struct LinkedList {
struct LinkedListNode *first;
struct LinkedListNode *last;
} LinkedList;
【问题讨论】:
-
为什么要分配内存给
Buckets-->newTable->Buckets = malloc(1009 * sizeof(LinkedList*));?Buckets已经是1009类型为LinkedList*的元素的数组。 -
一本好书Eternally Confuzzled - Hash Tables。非常值得一读。另一个来自耶鲁大学的C/HashTables 都很有帮助。收藏Coding a Hash Table
-
另外,除非你有一些无法解释的目的来使用桶的 双向链表,否则它通常是单向街道(例如 单向链表) 实现)在初始填充或重新散列以保持 负载因子 低于目标(通常
.7可以)时,您不会受益于双重链接
标签: c arrays pointers linked-list hashtable