c语言实现hashmap
时间: 2023-07-13 15:16:19 浏览: 60
实现哈希表(Hashmap)的基本思路是将键值对存储在一个数组中,通过哈希函数将键转换为数组的索引,然后将值存储在该索引处。
下面是一个简单的C语言实现哈希表的例子:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABLE_SIZE 100
typedef struct {
char* key;
int value;
} hash_node;
hash_node* hash_table[TABLE_SIZE];
int hash_function(char* key) {
int hash = 0;
for (int i = 0; i < strlen(key); i++) {
hash += key[i];
}
return hash % TABLE_SIZE;
}
void insert(char* key, int value) {
int index = hash_function(key);
if (hash_table[index] == NULL) {
hash_table[index] = malloc(sizeof(hash_node));
hash_table[index]->key = strdup(key);
hash_table[index]->value = value;
} else {
hash_node* node = hash_table[index];
while (node->next != NULL) {
node = node->next;
}
node->next = malloc(sizeof(hash_node));
node->next->key = strdup(key);
node->next->value = value;
}
}
int search(char* key) {
int index = hash_function(key);
hash_node* node = hash_table[index];
while (node != NULL) {
if (strcmp(node->key, key) == 0) {
return node->value;
}
node = node->next;
}
return -1;
}
int main() {
insert("apple", 1);
insert("banana", 2);
insert("orange", 3);
printf("apple = %d\n", search("apple"));
printf("banana = %d\n", search("banana"));
printf("orange = %d\n", search("orange"));
return 0;
}
```
这个例子中,我们使用一个简单的哈希函数,将字符串中所有字符的ASCII码之和作为哈希值。我们将哈希表的大小设为100,即数组的长度为100。如果两个不同的键具有相同的哈希值,我们采用链表的方式来处理冲突。
在主函数中,我们插入了三个键值对,然后通过搜索函数查找对应的值。运行程序,可以得到以下输出:
```
apple = 1
banana = 2
orange = 3
```
这表明我们的哈希表实现是正确的。当然,这只是一个简单的实现,实际应用中需要考虑更多的因素,例如哈希函数的设计、冲突处理的效率等。