CSDN=>FAQ=>FAQ 展示
  • 问题内容:c语言如何实现hashmap类型
  • 原讨论链接:http://community.csdn.net/expert/topicview1.asp?id=4867121
  • 所属论坛:数据结构与算法     审核组:其他
  • 提问者:wuallen     解决者:
  • 感谢:mathe
  • 关键字:专题开发/技术/项目 数据结构与算法 key value table next node hash_node hash_fun key_map hash_table mod
  • 答案:

    rt, 非常感谢!!!

    ---------------------------------------------------------------

    可以这样,比如从type1 到type2的hashmap
    typedef struct _hash_node{
       type1 key;
       type2 value;
       struct _hash_node *next;
    }*HASH_NODE;

    #define MOD 65521
    typedef unsigned (*HASH_FUN)(type1 key);
    typedef struct _hash_table{
        HASH_FUN  hash_fun;
        HASH_NODE vector[MOD];
    }HASH_TABLE;

    void init_hash_table(HASH_TABLE *table, HASH_FUN fun){
       int i;
       for(i=0;i<MOD;i++)table->vector[i]=NULL;
       table->hash_fun=fun;
    }

    void free_hash_table(HASH_TABLE *table){
      int i;
      for(i=0;i<MOD;i++){
        HASH_NODE node=table->vector[i];
        while(node){
            HASH_NODE next=node->next;
            free(node);
            node=next;
        }
      }
    }
    void insert_to_hash_table(HASH_TABLE *table, type1 key, type2 value){
       HASH_NODE node;
       unsigned key_map=table->hash_fun(key);
       key_map%=MOD;
       node = (HASH_NODE)malloc(sizeof(struct _hash_node));
       node->next=table->vector[key_map];
       table->vector[key_map]=node;
       node->key=key;
       node->value=value;
       
    }

    int find_in_hash_table(HASH_TABLE *table, type1 key, type2 *value)
    {
       HASH_NODE node;
       unsigned key_map=table->hash_fun(key);
       key_map%=MOD;
       node=table->vector[key_map];
       while(node){
           if(node->key==key){
                if(value){
                    *value=node->value;
                }
                return 1;/*found*/
           }
           node=node->next;
       }
       return 0; /*not found*/
    }

  • 评价: 有价值 给朵鲜花(0) 无价值 扔个鸡蛋(0)
相关FAQ
网站简介|广告服务|VIP资费标准|银行汇款帐号|网站地图|帮助|联系方式|诚聘英才|English|问题报告
北京创新乐知广告有限公司 版权所有, 京 ICP 证 070598 号
世纪乐知(北京)网络技术有限公司 提供技术支持
Copyright © 2000-2008, CSDN.NET, All Rights Reserved
GongshangLogo