通过三种hash函数将数据散列到对应的键值当中,而对于有冲突的键用链表储存数据。在这里只是用链表保存了与字符串首字母对应的指针,散列表的大小一般选择素数。参考书目《数据结构与算法分析》
//接口函数
#ifndef _HASH_H
#define _HASH_H
struct listnode
{
char *str;
struct listnode *Next;
};
typedef struct listnode ListNode;
typedef ListNode *Position;
struct HashTab
{
int TableSize;
Position *TheLists;
};
typedef struct HashTab *HashTable;
HashTable InitTable(int TableSize);
void DestroyTable(HashTable H);
Position Find(char *str,HashTable H);
void Insert(char *str,HashTable H);
void VisitAllList(HashTable H);
#endif
//接口函数定义
#include
#include
#include
#include "hash.h"
#define MinTableSize 2
typedef int Index;
Index Hash(const char *Key,int TableSize)//三种hash函数映射
{
unsigned int HashVal=0;
while(*Key!=0)
HashVal=(HashVal<<5)+*(Key++);
return HashVal%TableSize;
}
/*Index Hash(const char *Key,int TableSize)
{
unsigned int HashVal=0;
while(*Key!='\0')
HashVal+=*Key++;
return HashVal%TableSize;
}*/
/*Index Hash(const char *Key,int TableSize)
{
return (Key[0]+27*Key[1]+729*Key[2])%TableSize;
}*/
HashTable InitTable(int TabSize)
{
HashTable H;
int i;
if(TabSizeTableSize=TabSize;
H->TheLists=(ListNode **)malloc(sizeof(ListNode *)*H->TableSize);
if(H->TheLists==NULL)
printf("Out of space!!");
for(i=0;iTableSize;i++)
{
H->TheLists[i]=NULL;
}
return H;
}
Position Find(char *Key,HashTable H)
{
Position P;
P=H->TheLists[Hash(Key,H->TableSize)];
while(P!=NULL&&(strcmp(Key,P->str)!=0))
P=P->Next;
return P;
}
void Insert(char *Key,HashTable H) //映射到各个键值当中
{
Position NewCell,Pos;
int mod;
Pos=Find(Key,H);
if(Pos==NULL)
{
NewCell=(ListNode *)malloc(sizeof(ListNode));
if(!NewCell)
printf("Out of space");
else
{
mod=Hash(Key,H->TableSize); //链表储存(类似于栈储存)
NewCell->Next=H->TheLists[mod];
NewCell->str=Key;
H->TheLists[mod]=NewCell;
}
}
}
void VisitAllList(HashTable H)
{
int i;
Position P;
for(i=0;iTableSize;i++)
{
P=H->TheLists[i];
while(P!=NULL)
{
printf("%s ",P->str);
P=P->Next;
}
printf("\n");
}
}
void DestroyTable(HashTable H)
{
int i;
Position current,temp;
for(i=0;iTableSize;i++)
{
current=H->TheLists[i];
while(current!=NULL)
{
temp=current->Next;
free(current);
current=temp;
}
}
free(H->TheLists);
free(H);
}
//main函数入口
#include
#include "hash.h"
int main(int argc, char **argv)
{
int TabSize,i;
//char *buf="kindle";
char *buf[17]={"kiss","print","java","kugou","follow","scanf","rather","python","kidney","heaven",
"china","English","tell","again","begin","dance","write"};
HashTable H;
printf("Please enter the size of Hash Table:\n");
scanf("%d",&TabSize);
H=InitTable(TabSize);
for(i=0;i<17;i++)
{
Insert(buf[i],H);
}
VisitAllList(H);
DestroyTable(H);
return 0;
}
//测试结果
hash函数1
hash函数2
hash函数3
由于散列键值和散列元素选择较少无法体现三个hash函数的散列效果