#include<stdio.h>
#include<stdlib.h>
#ifndef _HashSep_H
struct ListNode;
typedef struct ListNode *ptr;
typedef ptr List;
struct HashTable;
typedef struct HashTbl *HashTable
HashTable newHashTable(int);
ptr Find(ElementType,HashTable);
void Insert(ElementType,HashTable);
void DetroyHashTable(HashTable);
#endif
struct ListNode
{
int element;
ptr next;
};
struct HashTbl
{
ElementType TableSize;
List *TheList;
};
HashTable newHashTable(int TableSize)
{
if(TableSize<MinTableSize)
exit(1); // 散列表尺寸太小
else
{
HashTable h=(HashTable)malloc(sizeof(struct HashTbl));
if(h==NULL)
exit(1); // 分配空间失败
else
{
h->TableSize=prime(TableSize); // 将用户预定尺寸换成接近的质数
h->TheList=(List *)malloc(sizeof(List)*h->TableSize); // 开辟一个数组空间存放指向链表的指针
if(h->TheList==NULL)
exit(1);
else
{
for(int step=0;step<h->TableSize;step++) // 数组初始化,建立一系列表头
{
h->TheList[step]=(List)malloc(sizeof(struct ListNode));
if(h->TheList[step]==NULL)
exit(1);
else
h->TheList[step]->next=NULL;
}
}
}
}
return h;
}
void Insert(ElementType x,HashTable h)
{
if(Find(x,h->TheList[hash(x,h->TableSize)])==NULL)
{
List tmp=(List)malloc(sizeof(struct ListNode));
if(tmp==NULL)
exit(1);
tmp->element=x;
tmp=h->TheList[hash(x,h->TableSize)]->next;
h->TheList[hash(x,h->TableSize)]->next=tmp;
}
}
ptr Find(ElementType x,HashTable h)
{
List l=h->TheList[hash(x,h->TableSize)];
ptr p=l->next;
while(p!=NULL&&p->element)
p=p->next;
return p;
}
void DestroyTable(HashTable h)
{
for(int step=0;step<h->TableSize;step++)
DestroyList(h->TheList[step]);
free(h);
}