本博文源于浙江大学的《数据结构》,散列的冲突解决方法有很多种,分离链接法算一种,下面就给出测试用例以及源码:
如果不了解散列表可参考这篇博文:
散列表基本常识(必知必会·理论篇)
测试用例
HashTable Tb = CreateTable(13);//创建哈希表
int flag = Insert(Tb,"abc");//往哈希表插入元素
flag = Insert(Tb,"def");//继续往哈希表插入元素
List Ltmp = Find(Tb,"abc");//寻找哈希表的位置
if(flag)
printf("Insert:Success\n");//观察插入数据状态
else
printf("Insert:Failed\n");
printf("%s\n",Ltmp->Data);//打印找到的值
flag = Insert(Tb,"abc");//插入一个已经有的值“abc”,观察是否成功
实验效果
源码
//分离链接方法.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdbool.h>
#include<math.h>
#define KEYLENGTH 15
#define MAXTABLESIZE 100000
typedef char ElementType[KEYLENGTH+1];
typedef int Index;
typedef struct LNode *PtrToLNode;
struct LNode {
ElementType Data;
PtrToLNode Next;
};
typedef PtrToLNode Position;
typedef PtrToLNode List;
typedef struct TblNode *HashTable;
struct TblNode {
int TableSize;
List Heads;
};
int NextPrime(int N)
{
int i,p=(N%2)?N+2:N+1;
while(p<=MAXTABLESIZE) {
for(i=(int)sqrt(p);i>2;i--)
if(!(p%i)) break;
if(i==2) break;
else p+=2;
}
return p;
}
int Hash(const char *Key,int TableSize) {
unsigned int H = 0;
while(*Key != '\0')
H = (H<<5)+* Key ++;
return H%TableSize;
}
HashTable CreateTable(int TableSize)
{
HashTable H;
int i;
H = (HashTable)malloc(sizeof(struct TblNode));
H->TableSize = NextPrime(TableSize);
H->Heads = (List)malloc(H->TableSize * sizeof(struct LNode));
for(i=0;i<H->TableSize;i++)
{
H->Heads[i].Data[0]='\0';
H->Heads[i].Next = NULL;
}
return H;
}
Position Find(HashTable H,ElementType Key)
{
Position P;
Index Pos;
Pos = Hash(Key,H->TableSize);
P = H->Heads[Pos].Next;
while(P && strcmp(P->Data,Key))
P = P->Next;
return P;
}
bool Insert(HashTable H,ElementType Key)
{
Position P,NewCell;
Index Pos;
P = Find(H,Key);
if(! P) {
NewCell = (Position)malloc(sizeof(struct LNode));
strcpy(NewCell->Data,Key);
Pos = Hash(Key,H->TableSize);
NewCell->Next = H->Heads[Pos].Next;
H->Heads[Pos].Next = NewCell;
}else {
printf("failed");
return false;
}
}
void DestroyTable(HashTable H) {
int i;
Position P,Tmp;
for(i=0;i<H->TableSize;i++) {
P = H->Heads[i].Next;
while(P) {
Tmp = P->Next;
free(P);
P = Tmp;
}
}
free(H->Heads);
free(H);
}
int main()
{
HashTable Tb = CreateTable(13);//创建哈希表
int flag = Insert(Tb,"abc");//往哈希表插入元素
flag = Insert(Tb,"def");//继续往哈希表插入元素
List Ltmp = Find(Tb,"abc");//寻找哈希表的位置
if(flag)
printf("Insert:Success\n");//观察插入数据状态
else
printf("Insert:Failed\n");
printf("%s\n",Ltmp->Data);//打印找到的值
flag = Insert(Tb,"abc");//插入一个已经有的值“abc”,观察是否成功
return 0;
}