C实现的Hash表

Hash表这种数据结构在java中是原生的一个集合对象,在实际中用途极广,主要有这么几个特点:

  1. 访问速度快
  2. 大小不受限制
  3. 按键进行索引,没有重复对象
  4. 用字符串(id:string)检索对象(object)

今天整理以前在学校写的一些算法,翻出来一个hash表的实现,就贴出来,自己也温习温习。
先看看头文件,也就是数据结构的定义,相当于java中的接口的概念:

<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--> #include  < stdio.h >

#define     HASHSIZE 256

//定义hash表中的节点的类型
struct     nlist{
    
struct     nlist     * next;
    
char      * name;
    
char      * defn;
};

//定义接口中的函数,也就是对外来说,这个程序可以做什么
unsigned    hash(
char   * s);//计算一个串的hash值
struct     nlist     * lookup( char   * s);//查找一个value,根据key
struct     nlist     * install( char   * name, char   * defn);//插入一个key=value的对象


然后是具体实现:

<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--> #include  < string .h >
#include 
" list.h "

static   struct  nlist  * hashtab[HASHSIZE];

unsigned    hash(
char   * s)
{
    unsigned    hashval;

    
for (hashval  =   0 * !=   ' \0 ' ;s ++ )
            hashval 
=   * +   31   *  hashval;
    
return  hashval  %  HASHSIZE;
}

struct     nlist     * lookup( char   * s)
{
    
struct     nlist     * np;

    
for (np  =  hashtab[hash(s)];
        np 
!=  NULL;
        np 
=  np -> next)
            
if (strcmp(s,np -> name)  ==   0 )
                    
return  np;
    
return  NULL;
}

struct     nlist     * install( char   * name, char   * defn)
{
    
struct     nlist     * np;
    unsigned    hashval;

    
if ((np  =  lookup(name))  ==  NULL){
        np 
=  ( struct  nlist  * )malloc( sizeof ( struct  nlist));
        
if (np  ==  NULL  ||  (np -> name  =  strdup(name))  ==  NULL)
                
return  NULL;
        hashval 
=  hash(name);
        np
-> next =  hashtab[hashval];
        hashtab[hashval] 
=  np;
    }
else
        free((
void   * )np -> defn);
    
if ((np -> defn  =  strdup(defn))  ==  NULL)
            
return  NULL;
    
return  np;
}

很简单,只有两个外部接口,

  1. install(key, value),用来插入一个新的节点
  2. lookup(key),根据一个键来进行搜索,并返回节点

代码很简单,主要用到的hash算法跟java中的String的hashcode()方法中用到的算法一样,使用:

 

<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />--> unsigned    hash( char   * s)
{
    unsigned    hashval;

    
for (hashval  =   0 * !=   ' \0 ' ;s ++ )
            hashval 
=   * +   31   *  hashval;
    
return  hashval  %  HASHSIZE;
}

 

这里的31并非随意,乃是一个经验值,选取它的目的在于减少冲突,当然,hash冲突这个问题是不能根本避免的。这里只是一个人们在测试中发现的可以相对减少hash冲突的一个数字,可能以后会发现更好的数值来。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值