c 语言实现hashmap示例代码
时间: 2023-08-31 12:41:01 浏览: 67
### 回答1:
在C语言中,可以使用结构体和指针来实现hashmap。下面是一个简单的实现示例代码:#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// 一个简单的结构体定义
struct map
{
char key[100];
char value[100];
};
// 初始化hash map
struct map *hashmap[10];
// hash函数
int hash(char *key)
{
int index;
int i;
int len = strlen(key);
for (i = 0; i < len; i++)
{
index += (int)key[i];
}
return index % 10;
}
// 插入hashmap
void insert(char *key, char *value)
{
// 计算hash值
int hash_index = hash(key);
// 找到空的位置
int i;
for (i = 0; i < 10; i++)
{
int index = (hash_index + i) % 10;
if (hashmap[index] == NULL)
break;
}
// 没有找到空的位置
if (i == 10)
return;
// 分配空间
struct map *temp = (struct map *)malloc(sizeof(struct map));
// 存储key、value
int len = strlen(key);
strncpy(temp->key, key, len);
len = strlen(value);
strncpy(temp->value, value, len);
// 插入hashmap
hashmap[index] = temp;
}
// 查找hashmap
char *get(char *key)
{
// 计算hash值
int hash_index = hash(key);
// 查找key
int i;
for (i = 0; i < 10; i++)
{
int index = (hash_index + i) % 10;
if (hashmap[index] == NULL)
break;
if (strcmp(hashmap[index]->key, key) == 0)
return hashmap[index]->value;
}
// 找不到key
return NULL;
}
### 回答2:
下面是一个简单的 C 语言实现 hashmap 的示例代码:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10 // hashmap 大小
typedef struct Node {
int key;
int value;
struct Node* next;
} Node;
typedef struct HashMap {
Node** array;
} HashMap;
// 创建一个新的节点
Node* createNode(int key, int value) {
Node* newNode = (Node*) malloc(sizeof(Node));
newNode->key = key;
newNode->value = value;
newNode->next = NULL;
return newNode;
}
// 创建一个新的 hashmap
HashMap* createHashMap() {
HashMap* hashMap = (HashMap*) malloc(sizeof(HashMap));
hashMap->array = (Node**) malloc(SIZE * sizeof(Node*));
for (int i = 0; i < SIZE; i++) {
hashMap->array[i] = NULL;
}
return hashMap;
}
// 计算哈希值
unsigned int hashCode(int key) {
return key % SIZE;
}
// 插入键值对
void insert(HashMap* hashMap, int key, int value) {
unsigned int hashIndex = hashCode(key);
Node* newNode = createNode(key, value);
// 如果该位置为空,直接插入
if (hashMap->array[hashIndex] == NULL) {
hashMap->array[hashIndex] = newNode;
}
// 否则,将新节点插入链表头部
else {
newNode->next = hashMap->array[hashIndex];
hashMap->array[hashIndex] = newNode;
}
}
// 查找值
int find(HashMap* hashMap, int key) {
unsigned int hashIndex = hashCode(key);
Node* currentNode = hashMap->array[hashIndex];
while (currentNode != NULL) {
if (currentNode->key == key) {
return currentNode->value;
}
currentNode = currentNode->next;
}
return -1;
}
int main() {
HashMap* hashMap = createHashMap();
insert(hashMap, 1, 10);
insert(hashMap, 2, 20);
insert(hashMap, 3, 30);
printf("%d\n", find(hashMap, 1));
printf("%d\n", find(hashMap, 2));
printf("%d\n", find(hashMap, 3));
return 0;
}
以上代码实现了一个简单的哈希表,使用链表解决冲突。其中,createNode() 函数用于创建一个新的节点,createHashMap() 函数用于创建一个新的 hashmap,hashCode() 函数用于计算哈希值,insert() 函数用于插入键值对,find() 函数用于查找给定键的值。最后,在 main() 函数中对 hashmap 进行测试,并输出相应的值。