//@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;
}
}
}
}
hashtable-1-c
最新推荐文章于 2020-09-04 11:53:19 发布