分离链接法的思路是将散列到同一个值的所以元素保留到一个表中。
头文件:
#ifndef HASHSEP_H_INCLUDED
#define HASHSEP_H_INCLUDED
struct ListNode;
typedef struct ListNode *Position;
struct HashTbl;
typedef struct HashTbl *HashTable;
typedef int ElementType;
HashTable InitializeTable(int TableSize);
void DestroyTable(HashTable H);
Position Find(ElementType Key,HashTable H);
void Insert(ElementType Key,HashTable H);
ElementType Retrieve(Position P);
#endif // HASHSEP_H_INCLUDED
实现: 这里ElementType以int为例,如要使用其他类型,需要重新设计散列函数
#include "HashSep.h"
#include <math.h>
#include <stdio.h>
#include <limits.h>
#define MinTableSize 10
struct ListNode
{
ElementType Element;
Position Next;
};
typedef Position List;
struct HashTbl
{
int TableSize;
List *TheLists;
};
int IsPrime(int num)
{
if(num == 1) return 0;
int i;
for(i = 2; i <= sqrt(num); i++)
if(num%i == 0)
return 0;
return 1;
}
int NextPrime(int TableSize)
{
int i;
for(i = TableSize; i < INT_MAX; i++)
if(IsPrime(i))
return i;
return 0;
}
void Error(char * s)
{
}
void FatalError(char * s)
{
}
/* Boss 散列函数 Function of Hash */
int Hash(const ElementType Key,int TableSize)
{
return Key%TableSize;
}
HashTable InitializeTable(int TableSize)
{
HashTable H;
int i;
if( TableSize < MinTableSize )
{
Error("Table size too small");
return NULL;
}
/*Allocate table*/
H = malloc(sizeof(struct HashTbl));
if(H == NULL)
FatalError("Out of space!!!");
H->TableSize = NextPrime(TableSize);
/*Allocate array of lists*/
H->TheLists = malloc(sizeof(List)*H->TableSize );
if(H->TheLists == NULL)
FatalError("Out of space!!!");
/* Allocate list headers */
for(i = 0; i < H->TableSize; i++)
{
H->TheLists[i] = malloc(sizeof(struct ListNode));
if(H->TheLists[i] == NULL)
FatalError("Out of space!!!");
else
H->TheLists[i]->Next = NULL;
}
return H;
}
Position Find(ElementType Key,HashTable H)
{
Position P;
List L;
L = H->TheLists[Hash(Key,H->TableSize)];
P = L->Next;
while( P != NULL && P->Element != Key )
P = P->Next;
return P;
}
void Insert(ElementType Key,HashTable H)
{
Position Pos,NewCell;
List L;
Pos = Find(Key,H);
if(Pos == NULL)
{
NewCell = malloc(sizeof(struct ListNode));
if(NewCell == NULL)
FatalError("Out of space!!!");
else
{
L = H->TheLists[Hash(Key,H->TableSize)];
NewCell->Next = L->Next;
NewCell->Element = Key;
L->Next = NewCell;
}
}
}
int main()
{
HashTable H = InitializeTable(1001);
int i;
for(i = 1; i <= 1000; i++)
Insert(i*2,H);
/*
Position P = Find(1001,H);
if(P != NULL)
printf("%d\n",P->Element);
else
printf("No data!!!\n");
return 0;
*/
for(i = 0; i < 1000; i++)
{
List L = H->TheLists[i];
Position P = L->Next;
while(P != NULL)
{
printf("%d ",P->Element);
P = P->Next;
}
printf("\n");
}
}
测试结果:
注:代码摘自《数据结构与算法分析第二版》