데이터 구조를 배우고 있습니다. 해시 테이블 (chaining/buckets)에 대한 크기 조정 함수를 만들어야합니다. 내 코드는 컴파일되지만 테이블 크기는 변경되지 않습니다. 누군가가 모양을 가지고 내가 크기 조정 기능에서 누락 된 것에 대한 팁을 줄 수 있습니까? 고맙습니다!이 크기 조정 기능은 어떻게 수정합니까?
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);
}
설명에 많은 시간을드립니다. resize 함수를 다시 시도했지만 여전히 고민 중입니다. 내 코드는 컴파일되지만 크기는 조정되지 않습니다. 내 크기 조정 기능을 업데이트했습니다. 좀 더 팁을 주겠니? – user2203774
@ user2203774 질문이나 채팅을 더 게시하기 만하면됩니다. – chux