用c写一个hashe map
时间: 2023-03-15 20:10:57 浏览: 101
C语言实现hashMap
4星 · 用户满意度95%
我可以为你编写一段示例代码,以供参考:```
#include <stdio.h>
#include <stdlib.h>// 定义一个hash map结构
typedef struct hashmap {
int key;
int value;
struct hashmap *next;
} hashmap;// 初始化一个hash map
hashmap *hashmap_init(){
hashmap *map = (hashmap *)malloc(sizeof(hashmap));
if(map == NULL) {
return NULL;
}
map->key = 0;
map->value = 0;
map->next = NULL;
return map;
}// 向hash map中添加新的键值对
int hashmap_put(hashmap *map, int key, int value) {
hashmap *tmp = map;
while(tmp->next != NULL){
tmp = tmp->next;
}
hashmap *new_node = (hashmap *)malloc(sizeof(hashmap));
new_node->key = key;
new_node->value = value;
new_node->next = NULL;
tmp->next = new_node;
return 0;
}// 从hash map中获取特定key的value
int hashmap_get(hashmap *map, int key) {
hashmap *tmp = map;
while(tmp != NULL){
if(tmp->key == key){
return tmp->value;
}
tmp = tmp->next;
}
return -1;
}int main(){
hashmap *map = hashmap_init();
hashmap_put(map, 1, 10);
hashmap_put(map, 2, 20);
hashmap_put(map, 3, 30); int value = hashmap_get(map, 2);
printf("value of key 2 is %d\n", value);
return 0;
}
```
阅读全文