#include#include #define A 1000 struct listnode{ char element; struct listnode* next; }H[A]; //直接用数组 typedef struct listnode list; int Hash(const char* key,int a){ unsigned int hashnum=0; while(*key!=' '){ hashnum=hashnum+*key++; } return hashnum%a; } //哈希函数 void Intital(list* H){ for(int i=0;i<1000;i++){ H[i].next=NULL; } } //初始化 list* Find(list*H,const char* key){ list p; list* l; p=H[Hash(key,A)]; l=p.next; while(l!=NULL && l->element!=*key){ l=l->next; } return l; } //查找数据 void Insert(list* H,const char* key){ list* p=Find(H,key); if(p==NULL){ list* m=(list*)malloc(sizeof(list)); m->element=*key; m->next=H[Hash(key,A)].next; H[Hash(key,A)].next=m; } } //插入(分离链表法) int main(void){ Intital(H); Insert(H,"a"); Insert(H,"c"); printf("%cn",Find(H,"a")->element); printf("%cn",Find(H,"c")->element); }
另一种形式
#include#include #define A 1000 struct listnode{ char element; struct listnode* next; }; typedef struct listnode* list; struct hash{ list *Thelist; }; typedef struct hash *Hashtbl; int Hash(const char* key,int a){ unsigned int hashnum=0; while(*key!=' '){ hashnum=hashnum+*key++; } return hashnum%a; } Hashtbl Intital(){ Hashtbl H=(Hashtbl)malloc(sizeof(struct hash)); H->Thelist=(list*)malloc(sizeof(list)*A); for(int i=0;iThelist[i]=(list)malloc(sizeof(struct listnode)); H->Thelist[i]->next=NULL; } return H; } list Find(Hashtbl H,const char* key){ list p,l; p=H->Thelist[Hash(key,A)]; l=p->next; while(l!=NULL && l->element!=*key){ l=l->next; } return l; } Hashtbl Insert(Hashtbl H,const char* key){ list p=Find(H,key); if(p==NULL){ list m=(list)malloc(sizeof(struct listnode)); m->element=*key; m->next=H->Thelist[Hash(key,A)]->next; H->Thelist[Hash(key,A)]->next=m; } return H; } int main(void){ Hashtbl H=Intital(); H=Insert(H,"a"); H=Insert(H,"c"); printf("%cn",Find(H,"a")->element); printf("%cn",Find(H,"c")->element); }



