不知道怎么解释,也懒得敲那么多废话,直接贴代码了!
.h文件
#ifndef __MAP_H__
#define __MAP_H__
#include "typedef.h"
typedef struct MapItem MapItem;
typedef struct Map Map;
struct MapItem{
MapItem* next;
void* value;
int key;
};
struct Map{
MapItem* mArr[1024];
};
my_extern void MapInit(Map* map);
my_extern void MapRelease(Map* map);
my_extern void MapSet(Map* map, int key, void* value);
my_extern void* MapGet(Map* map, int key);
#endif
.c文件
#include "Map.h"
#include "stdafx.h"
#include <stdlib.h>
#include "string.h"
void MapInit(Map* map){
int i = 1024;
while (i>=0 )
{
--i;
map->mArr[i] = NULL;
}
}
void MapSet(Map* map, int key, void* value){
MapItem* p;
p = (MapItem*)malloc(sizeof(MapItem));
if (map->mArr[key % 1024] == NULL)
{
map->mArr[key % 1024] = p;
p->key = key;
p->value = value;
p->next = NULL;
}
else
{
p->next = map->mArr[key % 1024];
map->mArr[key % 1024] = p;
p->key = key;
p->value = value;
}
}
void* MapGet(Map* map, int key){
MapItem* p;
p = map->mArr[key % 1024];
while (p != NULL)
{
if (p->key == key)
{
return p->value;
}
p = p->next;
}
return 0;
}

本文介绍了一种简易的哈希表实现方式,通过C语言代码展示了哈希表的基本操作,包括初始化、设置值和获取值等。该实现采用链地址法解决冲突,适合初学者理解哈希表的工作原理。

被折叠的 条评论
为什么被折叠?



