hashmap

typedef int (* HashKeyCmpFun)(const void *key1, const void key2);
typedef int (
HashCalFun)(const void *key);
typedef struct HashNode {
void *key;
int value;
struct HashNode *next;
} HashNodeT;

typedef struct {
HashNodeT *entry;
} BucketT;

typedef struct {
HashKeyCmpFun keyCmpFun;
HashCalFun hashCalFun;
int bucketNum;
BucketT bucket[];
} HashMapT;

HashMapT *HashInit(int bucketNum, HashKeyCmpFun keyCmpFun, HashCalFun hashCalFun)
{
HashMapT *hashMap = (HashMapT *)malloc(sizeof(HashMapT) + bucketNum * sizeof(BucketT));
if (hashMap == NULL) {
return NULL;
}
memset(hashMap, 0, sizeof(HashMapT) + bucketNum * sizeof(BucketT));
hashMap->keyCmpFun = keyCmpFun;
hashMap->hashCalFun = hashCalFun;
hashMap->bucketNum = bucketNum;
return hashMap;
}

int HashInsert(HashMapT *hashMap, void *key, int value)
{
int hash = hashMap->hashCalFun(key);
int capticy = hashMap->bucketNum;
HashNodeT *node = (HashNodeT *)malloc(sizeof(HashNodeT));
if (node == NULL) {
return -1;
}
node->key = key;
node->value = value;
HashNodeT *entry = hashMap->bucket[hash % capticy].entry;
node->next = entry;
hashMap->bucket[hash % capticy].entry = node;
return 0;
}

int HashGet(HashMapT *hashMap, void *key)
{
int hash = hashMap->hashCalFun(key);
int capticy = hashMap->bucketNum;
HashNodeT *entry = hashMap->bucket[hash % capticy].entry;
while (entry != NULL) {
if (hashMap->keyCmpFun(key, entry->key) == 1) {
return entry->value;
}
entry = entry->next;
}
return -1;
}

void HashDelete(HashMapT *hashMap)
{
int capticy = hashMap->bucketNum;
for (int i = 0; i < capticy; i++) {
HashNodeT *entry = hashMap->bucket[hash % capticy].entry;
while (entry != NULL) {
HashNodeT *tmp = entry->next;
// key value看情况释放
free(entry);
entry = tmp;
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值