用c写一个hash map
时间: 2023-03-15 22:10:57 浏览: 121
C语言实现hashMap
4星 · 用户满意度95%
我可以为你提供一些关于用C语言实现哈希表的示例代码:#include<stdio.h>
#include<stdlib.h>
#include<string.h>// 定义哈希表节点
struct HashNode
{
char *key;
int value;
struct HashNode *next;
};// 定义哈希表
struct HashMap
{
int size;
struct HashNode **table;
};struct HashMap *createHashMap(int size)
{
struct HashMap *map = (struct HashMap*)malloc( sizeof(struct HashMap) );
map->size = size;
map->table = (struct HashNode**)calloc( size, sizeof(struct HashNode*) );
int i;
for(i=0; i<size; i++)
{
map->table[i] = NULL;
}
return map;
}int hashFunc(struct HashMap *map, char *key)
{
int seed = 131;
int hash = 0;
while (*key)
{
hash = hash * seed + (*key++);
}
return (hash & 0x7FFFFFFF) % map->size;
}void insertHashMap(struct HashMap *map, char *key, int value)
{
int hash_val = hashFunc(map, key);
struct HashNode *node = (struct HashNode*)malloc( sizeof(struct HashNode) );
node->key = key;
node->value = value;
node->next = map->table[hash_val];
map->table[hash_val] = node;
}int searchHashMap(struct HashMap *map, char *key)
{
int hash_val = hashFunc(map, key);
struct HashNode *node = map->table[hash_val];
while (node)
{
if (strcmp(node->key, key) == 0)
return node->value;
node = node->next;
}
return -1;
}void deleteHashMap(struct HashMap *map, char *key)
{
int hash_val = hashFunc(map, key);
struct HashNode *node = map->table[hash_val];
struct HashNode *prev;
while (node)
{
if (strcmp(node->key, key) == 0)
{
if (node == map->table[hash_val])
{
map->table[hash_val] = node->next;
}
else
{
prev->next = node->next;
}
free(node);
}
prev = node;
node = node->next;
}
}
阅读全文