本文以C语言描述散列,其中哈希函数可根据自己需要更改,以下是源代码:
#include "HashSep.h"
typedef uint64_t Index;
static Index Hash(const char *Key, uint64_t TableSize)
{
Index HashVal = 0;
while ('\0' != *Key)
{
HashVal = (HashVal << 5) + *Key++;
}
return HashVal%TableSize;
}
static bool IsPrime(uint64_t n)
{
if ((1 == n) || (2 == n) || (0 == (n % 2)))
return false;
for (uint64_t i = 3; i*i < n; i += 2)
{
if (0 == n%i)
return false;
}
return true;
}
static uint64_t NextPrime(uint64_t n)
{
while (!IsPrime(n++));
return --n;
}
HashTable InitializeTable(uint64_t TableSize)
{
HashTable H;
if (TableSize < MINTABLESIZE)
{
printf("Table size is too small!\r\n");
return NULL;
}
H = (HashTable)malloc(sizeof(HashTbl));
if (NULL == H)
{
printf("Out of space!\r\n");
return NULL;
}
H->TableSize = NextPrime(TableSize);
H->TheLists = malloc(H->TableSize * sizeof(List));
if (NULL == H->TheLists)
{
printf("Out of size!\r\n");
return NULL;
}
for (uint64_t i = 0; i < H->TableSize; i++)
{
H->TheLists[i] = (Position)malloc(sizeof(ListNode));
if (NULL == H->TheLists[i])
{
printf("Out of space!\r\n");
return NULL;
}
H->TheLists[i]->Next = NULL;
}
return H;
}
void DestoryTable(HashTable H);
Position Find(HashTable H, ElementType Key)
{
Position P;
List L;
L = H->TheLists[Hash(Key, H->TableSize)];
P = L->Next;
while (NULL != P && strcmp(Key, P->Element))
{
P = P->Next;
}
return P;
}
void Insert(HashTable H, ElementType Key)
{
Position Pos, NewCell;
List L;
Pos = Find(H, Key);
if (NULL == Pos)
{
NewCell = (Position)malloc(sizeof(ListNode));
if (NULL == NewCell)
{
printf("Out of space!\r\n");
}
else
{
L = H->TheLists[Hash(Key, H->TableSize)];
NewCell->Next = NULL;
NewCell->Element = Key;
L->Next = NewCell;
}
}
}
ElementType Retrieve(Position P);
#ifndef __HashSep_H_
#define __HashSep_H_
#include "stdint.h"
#include "stdio.h"
#include "malloc.h"
#include "string.h"
#include "stdbool.h"
#include "stdlib.h"
#define MINTABLESIZE 3
typedef char *ElementType;
typedef struct node
{
ElementType Element;
struct node *Next;
} ListNode;
typedef ListNode *Position;
typedef Position List;
typedef struct
{
uint64_t TableSize;
List *TheLists;
} HashTbl;
typedef HashTbl *HashTable;
HashTable InitializeTable(uint64_t TableSize);
void DestoryTable(HashTable H);
Position Find(HashTable H, ElementType Key);
void Insert(HashTable H, ElementType Key);
ElementType Retrieve(Position P);
#endif