lvxuzhou


私信TA

用户名:lvxuzhou

访问量:97346

签 名:

lvxuzhou

等  级
排  名 48
经  验 11191
参赛次数 0
文章发表 56
年  龄 0
在职情况 学生
学  校 西安
专  业

  自我简介:

TA的其他文章

ZeroMQ 基础一
浏览:106

C语言实现hashmap的方式有很多,最简单的就是使用数组实现,个人原创,源码如下:

#include <stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct hashnode
{
    char key[10];        //键
    int value;           //值
};
typedef struct 
{
    int size;
    int length;
    struct hashnode*Array;
}Hashmap;
Hashmap*hashmap;
unsigned int hash_33(char* key)//哈希算法
{
    unsigned int hash = 0;
    while (*key) 
    {
        hash = (hash << 5) + hash + *key++;
    }
    return hash;
}
void init()//初始化哈希表
{
    int i=0;
    hashmap=(Hashmap*)calloc(10,sizeof(Hashmap));
    for(i=0;i<10;i++)
    {
    hashmap[i].Array=(struct hashnode*)calloc(10,sizeof(struct hashnode));
    hashmap[i].size=10;
    hashmap[i].length=0;
    }
}
void add(char* key,int value)//添加key-value
{
    int hashcode=hash_33(key)%10;
    Hashmap* hm=hashmap+hashcode;
    int index=hm->length;
    int i;
    if (index>=hm->size)//数组扩容
    {
        int size=hm->size*2;
        hm->Array=(struct hashnode*)realloc(hm->Array,size*sizeof(struct hashnode));
        hm->size=size;
    }
    for(i=0;i<hm->size;i++)
    {
        if (strcmp(hm->Array[i].key,key)==0)//key相同就覆盖
        {
            hm->Array[i].value=value;
            break;
        }
        else
        {
            strcpy(hm->Array[i].key,key);
            hm->Array[i].value=value;
            hm->length++;
            break;
        }
    }
}
void print()//遍历哈希表
{
    int i,j;
    if (hashmap==NULL)
    {
        puts("hashmap为空");
        return;
    }
    for (i=0;i<10;i++)
    {
        Hashmap sm=hashmap[i];
        putchar('|');
        for (j = 0; j < sm.length; j++)
        {
           printf("%s=%d",sm.Array[j].key,sm.Array[j].value);
        }
        printf("|\n");
    }
}
void empty()    //清空哈希表
{
    int i,j;
    for (i=0;i<10;i++)
    {
        Hashmap* sm=hashmap+i;
        free(sm->Array);
        sm->Array=NULL;
    }
    free(hashmap);
    hashmap=NULL;
}
int main(void)
{
    init();
    add("a",1);
    add("b",1);
    add("a",2);
    add("c",1);
    add("d",10);
    add("a",1);
    add("b",1);
    add("a",2);
    add("c",1);
    add("d",10);
    print();
    empty();
    print();
    getchar();
    return 0;
}

目前只支持增加、遍历、清空功能。

有兴趣的读者可以自行实现删除、查找、替换.......等功能。

运行结果如图:

QQ图片20180704103401.png

欢迎交流

个人QQ:757368775 

【注意】

添加好友时请注明“来自c语言网”


 

0.0分

0 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区