C++ Map(list与数组的结合char型)(hash算法.)

//注意char类型的map是需要用字符串判断所get的key是否与存储的key相等的,所以不再是map->key == key;
//这里要注意,还有,一开始我做的时候不明白为什么hash要*33,后来明白,其实是冲突防止会分布不均匀,因为hash需要的就是提高效率,所以*33拉开距离,使得存储尽可能的均匀,当然因为所得数字肯定是会很大的,所以还是一样用了hash的取余法再次进行取余分配到1024数组中。

.c文件
#ifndef __MAP_H__
#define __MAP_H__
#include "typedef.h"

typedef struct MapItem  MapItem;
typedef struct Map  Map;

struct MapItem{
    MapItem* next;
    void* value;
    char* key;
};

struct Map{
    MapItem* mArr[1024];
};

my_extern void MapInit(Map* map);
my_extern void MapSet(Map* map, char* key, void* value);
my_extern void* MapGet(Map* map, char* key);
my_extern int my_strcmp(const char* str1, const char* str2);
my_extern unsigned int Hash33(char *str);
my_extern char* strCopy(char* str);

#endif


.h文件
#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, char* key, void* value){
    MapItem* p;

    int strKey = Hash33(strCopy(key));
    p = (MapItem*)malloc(sizeof(MapItem));

    if (map->mArr[strKey % 1024] == NULL)
    { 
        map->mArr[strKey % 1024] = p;
        p->key = key;
        p->value = value;
        p->next = NULL;
    }
    else
    {
        p->next = map->mArr[strKey % 1024];
        map->mArr[strKey % 1024] = p;
        p->key = key;
        p->value = value;
    }
}


void* MapGet(Map* map, char* key){
    MapItem* p;
    int strKey = Hash33(strCopy(key));
    p = map->mArr[strKey % 1024];
    while (p != NULL)
    {
        if (my_strcmp(p->key,key)==0)
        {
            return p->value;
        } 
            p = p->next;
    }
    return 0;
}
char* strCopy(char* str){
    int keyNum = strlen(str) + 1;
    char *keyHash = (char*)malloc(keyNum);
    char *keyHash2 = keyHash;
    while (*str != '\0')
    {
        *keyHash++ = *str++;
        printf("%s", keyHash2);
    }
    *keyHash = '\0';
    printf("%s", keyHash2);
    return keyHash2;
}

unsigned int Hash33(char *str)
{
    unsigned int hash = 0;
    while (*str)
    {
        hash = hash*33 + (*str++);
    }
    return hash;
}
int my_strcmp(const char* str1, const char* str2){
    while (*str1 != '\0' || *str2 != '\0')
    { 
        if (*str1 == *str2)
        {
            *str1++;
            *str2++;
            continue;
        }
        else if (*str1 < *str2)
        {
            *str1++;
            *str2++;
            return -1;
        }
        else if (*str1 > *str2)
        {
            *str1++;
            *str2++;
            return 1;
        }
    }
    return 0;   
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值