int hash_insert(HashTable *ht, char *key, void *value) |
{ |
// check if we need to resize the hashtable |
resize_hash_table_if_needed(ht); // 哈希表不固定大小,当插入的内容快占满哈表的存储空间 |
// 将对哈希表进行扩容, 以便容纳所有的元素 |
|
int index = HASH_INDEX(ht, key); // 找到key所映射到的索引 |
|
Bucket *org_bucket = ht->buckets[index]; |
Bucket *bucket = (Bucket *)malloc(sizeof(Bucket)); // 为新元素申请空间 |
|
bucket->key = strdup(key); |
// 将值内容保存进来, 这里只是简单的将指针指向要存储的内容,而没有将内容复制。 |
bucket->value = value; |
|
LOG_MSG( "Insert data p: %p\n" , value); |
|
ht->elem_num += 1; // 记录一下现在哈希表中的元素个数 |
|
if (org_bucket != NULL) { // 发生了碰撞,将新元素放置在链表的头部 |
LOG_MSG( "Index collision found with org hashtable: %p\n" , org_bucket); |
bucket->next = org_bucket; |
} |
|
ht->buckets[index]= bucket; |
|
LOG_MSG( "Element inserted at index %i, now we have: %i elements\n" , |
index, ht->elem_num); |
|
return SUCCESS; |
} |