hashtable-1-c

//@file hashtest.c
//compiled with vc++6.0
#include "hash.h"
int main(){
  int i;
  char* key[]={"name","address","phone","door","city"};
  char* value[]={"netboy","china","263788","110#","guangzhou"};

  InitHashTable();
  for(i=0;i<5;i++) { inputdatatohash(key[i],value[i]);}

  printf("测试开始.../n");
  printf("phone=%s/n",getvaluefromhash("phone"));
  //修改键值对为"phone","020-69854124";
  inputdatatohash("phone","020-69854124");
  printf("phone=%s/n",getvaluefromhash("phone"));
  printf("city=%s/n",getvaluefromhash("city"));
  //printhashtable();
  clearhashtable();
  return 0;
}
/*
运行结果
测试开始...
phone=263788
phone=020-69854124
city=guangzhou
*/
//@file hash.h
//compiled with vc++6.0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 101

typedef struct _node{
  char *name;
  char *desc;
  struct _node *next;
}node;

static node* hashtab[SIZE];

//1.初始化InitHashTable()
void InitHashTable(){
  int i;
  for(i=0;i<SIZE;i++)
    hashtab[i]=NULL;
}
//2.哈希随机数hash(char *)
unsigned int hash(char *s){
  unsigned int h=0;
  //简单的hash()
  for(;*s;s++)
    h=*s+h*31;
  return h%SIZE;
}

//3.查找函数find(char *n)
node* find(char *n){
  unsigned int hi=hash(n);
  node* np=hashtab[hi];
  for(;np!=NULL;np=np->next){
    if(!strcmp(np->name,n))
      return np;
  }
  return NULL;
}

//4.重复n个字符strndup(char *o)
char* strndup(char *o){
  int l=strlen(o)+1;
  char *ns=(char*)malloc(l*sizeof(char));
  strcpy(ns,o);
  if(ns==NULL)
    return NULL;
  else
    return ns;
}
//5.从hashtable取值
char* getvaluefromhash(char* name){
  node* n=find(name);
  if(n==NULL)
    return NULL;
  else
    return n->desc;
}
//6.数据输入hashtable
int inputdatatohash(char* name,char* desc){
  unsigned int hi;
  node* np;
  if((np=find(name))==NULL){
    hi=hash(name);
    np=(node*)malloc(sizeof(node));
    if(np==NULL)
      return 0;
    np->name=strndup(name);
    if(np->name==NULL) return 0;
    np->next=hashtab[hi];
    hashtab[hi]=np;
  }
  else
    free(np->desc);
  np->desc=strndup(desc);
  if(np->desc==NULL) return 0;

  return 1;
}
//7.打印hashtable表的值
void printhashtable(){
  int i;
  node *t;
  for(i=0;i<SIZE;i++){
    if(hashtab[i]==NULL)
      printf("[]");
    else
    {
      t=hashtab[i];
      for(;t!=NULL;t=t->next)  printf("[%s.%s]",t->name,t->desc);
    }
  }
}

void clearhashtable(){
  int i;
  node *np,*t;
  for(i=0;i<SIZE;i++){
    if(hashtab[i]!=NULL){
      np=hashtab[i];
      while(np!=NULL){
    t=np->next;
    free(np->name);
    free(np->desc);
    free(np);
    np=t;
      }
    }
  }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值