#define MinTableSize 10//最小表大小
#define NULLUNM -32789
struct ListNode;
struct HashTbl;
typedef struct ListNode *Position;
typedef Position List;
typedef struct HashTbl *HashTable;
struct ListNode//链表
{
int Element;
Position Next;
};
struct HashTbl//hash表
{
int TableSize;//hash表的大小(链表个数)
List *TheLists;//链表类型的数组。TheList是数组首地址
};
int IsPrimeNum1(int X)
{
if (X == 1 || X == 2)
{
return 1;
}
else
{
for (int i = 2; i < X; i++)
{
if (X%i == 0)
{
return 0;
}
}
return 1;
}
}
int NextPrime(int inputSize)
{
int input = inputSize;
if (IsPrimeNum1(inputSize))
{
return inputSize;
}
else
{
while (!IsPrimeNum1(input))
{
input++;
}
return input;
}
}
HashTable InitializeTable(int TableSize)
{
HashTable H;
int i;
if (TableSize < MinTableSize)
{
return NULL;
}
H = (HashTable)(malloc(sizeof(struct HashTbl)));
if (H == NULL)
{
return NULL;
}
H->TableSize = NextPrime(TableSize);
H->TheLists = (List*)(malloc(sizeof(struct ListNode)*H->TableSize));
if (H->TheLists == NULL)
{
return NULL;
}
for (i = 0; i < H->TableSize; i++)
{
H->TheLists[i] = (List)(malloc(sizeof(struct ListNode)));
if (H->TheLists[i] == NULL)
{
return NULL;
}
else
{
H->TheLists[i]->Next = NULL;
H->TheLists[i]->Element = NULLUNM;
}
}
printf_s("Initialized\n");
return H;
}
typedef unsigned int Index;
Index Hash(const int key, int TableSize)
{
Index hash;
int tmp = key;
if (key < 0)
tmp = key * -1;
hash = tmp % TableSize;
return hash;
}
Position Find(const int key, HashTable H)
{
Position p;
List L;
Index index = Hash(key, H->TableSize);
L = H->TheLists[index];
p = L;
while (p != NULL && p->Element != key&&p->Element!= NULLUNM)
{
p = p->Next;
}
return p;
}
void Insert(const int key, HashTable H)
{
Position Pos, NewCell;
List L;
Pos = Find(key,H);
if (Pos == NULL)
{
NewCell = malloc(sizeof(struct ListNode));
L = H->TheLists[Hash(key, H->TableSize)];
NewCell->Next = L->Next;
NewCell->Element = key;
L->Next = NewCell;
}
else if(Pos->Element= NULLUNM)
{
Pos->Element = key;
}
}