/*
* hashsep.cpp
*/
#include
#include
#include "fatal.h"
#include "hashsep.h"
#define MinTableSize (10)
struct ListNode
{
ElementType Element;
Position Next;
};
typedef Position List;
/*
* List *TheLists will be an array of lists, allocated later.
* The lists use headers(for simplicity), though this waste space.
*/
struct HashTbl
{
int TableSize;
List *TheLists;
};
/*
* Return next prime; assume N >= 10.
*/
static int NextPrime(int N)
{
int i;
if (N % 2 == 0)
{
++N;
}
for ( ; ; N += 2)
{
for (i = 3; i * i <= N; i += 2)
{
if (N % i == 0)
{
goto ContOuter; /* Sorry about this! */
}
}
return N;
ContOuter:;
}
}
HashTable InitializeTable(int TableSize)
{
HashTable H;
int i;
if (TableSize < MinTableSize)
{
FatalError("Table size too small!");
}
H = (HashTable)malloc(sizeof(struct HashTbl));
if (H == NULL)
{
FatalError("Out of space!");
}
H->TableSize = NextPrime(TableSize);
/* Allocate array of lists */
H->TheLists = (List *)malloc(sizeof(List)* H->TableSize);
if (H->TableSize == NULL)
{
FatalError("Out of space!");
}
/* Allocate list headers */
for (i = 0; i < H->TableSize; ++i)
{
H->TheLists[i] = (List)malloc(sizeof(struct ListNode));
if (H->TheLists[i] == NULL)
{
FatalError("Out of space!");
}
else
{
H->TheLists[i]->Next = NULL;
}
}
return H;
}
/*
* Hash function for ints
*/
Index Hash(ElementType Key, int TableSize)
{
return Key % TableSize;
}
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;
}
/*
* Place the item at the front of the list.
*/
void Insert(ElementType Key, HashTable H)
{
Position Pos, NewCell;
List L;
Pos = Find(Key, H);
if (Pos == NULL) /* Key is not found */
{
NewCell = (List)malloc(sizeof(ListNode));
if (NewCell == NULL)
{
FatalError("Out of space!");
}
else
{
L = H->TheLists[Hash(Key, H->TableSize)];
NewCell->Next = L->Next;
L->Next = NewCell;
NewCell->Element = Key;
}
}
}
ElementType Retrieve(Position P)
{
return P->Element;
}
void DestroyTable(HashTable H)
{
Position P, Tmp;
int i;
for (i = 0; i < H->TableSize; ++i)
{
P = H->TheLists[i];
while (P != NULL)
{
Tmp = P->Next;
free(P);
P = Tmp;
}
}
free(H->TheLists);
free(H);
}
void PrintElements(HashTable H)
{
Position P;
List L;
for (int i = 0; i < H->TableSize; ++i)
{
L = H->TheLists[i];
P = L->Next;
printf("%2d: ", i);
while (P != NULL)
{
printf("%d ", P->Element);
P = P->Next;
}
printf("\n");
}
}