#ifndef _HASH_H_
#define _HASH_H_
typedef struct hashmap_node
{
struct hashmap_node *next;
char *key;
void *value;
}hashmap_node_t;
typedef struct hashmap
{
hashmap_node_t *hashmap_link;//记录hashmap链表头节点位置
unsigned int length;
}hashmap_t;
hashmap_t *init(void);
int ins_hash(hashmap_t *hashmap,const char *key,const void *value,unsigned int size);
int del_hash(hashmap_t *hashmap,const char *key);
int mod_hash(hashmap_t *hashmap,const char *key,const void *value);
int find_hash(hashmap_t *hashmap,const char *key);
int destroy(hashmap_t *hashmap);
#endif //HASH_H_
#include<stdio.h>
#include<stdlib.h>
#include"hash.h"
#include<string.h>
hashmap_t *init(void)
{
hashmap_t *hashmap = NULL;
hashmap = (hashmap_t *)malloc(sizeof(hashmap_t));
if(hashmap == NULL)
{
return NULL;
}
hashmap->hashmap_link = (hashmap_node_t *)malloc(sizeof(hashmap_node_t));
if(hashmap->hashmap_link == NULL)
{
free(hashmap);
return NULL;
}
hashmap->hashmap_link->next = NULL;
hashmap->length = -1;
return hashmap;
}
int ins_hash(hashmap_t *hashmap,const char *key,const void *value,unsigned int size)
{
hashmap_node_t *new_node = NULL;
new_node = (hashmap_node_t *)malloc(sizeof(hashmap_node_t));
if (new_node == NULL)
{
return -1;
}
printf("success create new_node\n");
if(find_hash(hashmap,key)==0)
{
new_node->next = hashmap->hashmap_link->next;
hashmap->hashmap_link->next = new_node;
printf("2\t");
strcpy(new_node->key,key);
new_node->value = malloc(size);
memcpy(new_node->value,value,size);
hashmap->length ++;
return 0;
}
return -2;
}
int del_hash(hashmap_t *hashmap,const char *key);
int mod_hash(hashmap_t *hashmap,const char *key,const void *value);
//成功找到返回1 失败返回0
int find_hash(hashmap_t *hashmap,const char *key)
{
hashmap_node_t *find_node = NULL;
find_node = (hashmap_node_t *)malloc(sizeof(hashmap_node_t));
printf("find_node success create\n");
for(find_node = hashmap->hashmap_link->next ; find_node != NULL; find_node = find_node->next)
{
if(strcmp(find_node->key,key)==0)
return 1;
}
return 0;
}
https://blog.csdn.net/qq_38513966/article/details/84792960