我正在学习数据结构。我需要为哈希表(链接/桶)创建一个调整大小的函数。我的代码可以编译,但表大小从未改变。有人可以看看并给我一些关于我在调整大小功能中缺少的提示吗?谢谢!
struct hlink {
TYPE value;
struct hlink *next;
};
struct hashTable {
struct hlink **table;
int tableSize;
int count;
};
void initHashTable (struct hashTable *ht, int size ) {
assert (size > 0);
//allocate memory for table
ht->table = (struct hlink **) malloc(size * sizeof(struct hlink *));
assert(ht->table != 0);
//initialize empty link list
int i;
for (i = 0; i < size; i++)
{
ht->table[i] = 0;
}
//set tableSize to be size
ht->tableSize = size;
ht->count = 0;
}
void _resizeHashTable(struct hashTable *ht)
{
//create and initialize new tablesize
int new_tblSize = 2 * ht->tableSize;
//old list
struct hlink **oldList = ht->table;
//new list
struct hlink **newList = (struct hlink **) malloc(new_tblSize * sizeof(struct hlink*));
//Copy old values to new table
for (int i=0; i < new_tblSize; i++)
{
//compute hash value to find the new bucket
int hashIndex = HASH(oldList[i]->value) % new_tblSize;
if (hashIndex < 0)
hashIndex += new_tblSize;
newList[i]->value = oldList[i]->value;
newList[i]->next = newList[hashIndex];
}
//Assign table and tablesize back to the old table
free(ht->table);
ht->table = newList;
ht->tableSize = new_tblSize;
}
void hashTableAdd (struct hashTable *ht, TYPE newValue)
{
// compute hash value to find the correct bucket
int hashIndex = HASH(newValue) % ht->tableSize;
if (hashIndex < 0)
hashIndex += ht->tableSize;
struct hlink * newLink = (struct hlink *) malloc(sizeof(struct hlink));
assert(newLink != 0);
newLink->value = newValue;
newLink->next = ht->table[hashIndex];
ht->table[hashIndex] = newLink; //add to bucket
ht->count++;
if ((ht->count / (double) ht->tableSize) > 8.0)
_resizeHashTable(ht);
}