#include <stdio.h>
#include <stdlib.h>
#define MinSize 10
struct ListNode;
typedef struct ListNode* Position;
struct HashTabl;
typedef struct HashTbl* HashTable;
struct ListNode {
int element;
Position next;
};
typedef Position List;
struct HashTbl {
int TableSize;
List* TheLists;
};
HashTable InitializeTable(int TableSize);
void DestroyTable(HashTable H);
Position Find(int Key, HashTable H);
int Retrieve(Position P);
HashTable Initialize(int TableSize)
{
if (TableSize < MinSize)
{
Error("No Space!!");
return NULL;
}
HashTable H = malloc(sizeof(struct HashTbl));
if (H == NULL)
FatalError("No Space!!");
H->TableSize = TableSize;
H->TheLists = malloc(sizeof(List) * TableSize);
if (H->TheLists == NULL)
FatalError("No Space!!");
int i;
for (i = 0; i < TableSize; i++)
{
H->TheLists[i] = malloc(sizeof(struct ListNode));
if (H->TheLists[i] == NULL)
FatalError("No Space!!");
else
H->TheLists[i] = NULL;
}
return H;
}
int Hash(int x, int TableSzie);
Position Find(int x, HashTable H)
{
int index = Hash(x, H->TableSize);
List L = H->TheLists[index];
Position P = L->next;
while (P->element != x && P->next != NULL)
P = P->next;
return P;
}
void Insert(int x, HashTable H)
{
int index = Hash(x, H->TableSize);
List L = H->TheLists[index];
Position P = Find(x, H);
if (P == NULL)//先检查里面有没有过
{
Position new = malloc(sizeof(struct ListNode));
if (new == NULL)
Error("No Space!!");
else
{
new->element = x;
new->next = L->next;
L->next = new;
}
}
}
void Delete(int x, HashTable H)
{
Position pos = Find(x, H);
if (pos != NULL)
{
Position temp = pos->next;
pos->next = temp->next;
free(temp);
}
}