//结构定义
#define HASHNUM 13
typedef unsigned int KeyType;
typedef struct {}DataType;
typedef struct HashNode
{
KeyType key;
DataType data;
HashNode *next;
}HashNode ;
typedef struct Hash
{
HashNode *hashTable[HASHNUM];
}Hash;
//初始化
void InitHash(MyHash *hash)
{
if(hash == NULL) exit(0);
for(int i ; i<HASHNUM ; ++i)
{
hash->hashTable[i] = NULL;
}
}
//哈希函数 散列函数
static int Hash(KeyType key)
{
return key % HASHNUM;
}
//寻找
static int SearchNot(MyHash *hash , KeyType key , int pos)
{
HashNode *p = hash ->hashTable[pos];
while(p != NULL)
{
if(p->key == key)
{
return 0;
}
p = p->next;
}
return 1;
}
HashNode *Search(MyHash *hash , KeyType key)
{
if(hash == NULL) exit(0);
HashNode *p = hash->hashTable[Hash(key)];
while(p != NULL)
{
if(p->key == key)
{
return p;
}
p = p->next;
}
return NULL;
}
//创建新结点
static HashNode *_ApplyNode(KeyType key , HashNode *next)
{
HashNode *s = (HashNode *)malloc(sizeof(HashNode ));
if(s == NULL) exit(0);
s->key = key;
s->next = next;
return 0;
}
//插入
void InterHash(MyHash *hash , KeyType key )
{
if(hash == NULL) exit(0);
int pos =Hash(key);
if(SearchNot (hash , key , pos))
{
hash->hashTable[pos] = _ApplyNode(key , hash->hashTable[pos]);
if(s == NULL)
{
hash->hashTable[pos] = s;
return 1;
}
return 0;
}
//删除
void DeleteHash(MyHash *hash , KeyType key)
{
if(hash == NULL) exit(0);
int pos = Hash(key);
HashNode *p = hash->hashTable[pos];
HashNode *pr = NULL;
while(p != NULL)
{
if(p->key == key)
{
break;
}
pr = p;
p=p->next;
}
if(p == NULL)
{
return 0;
}
//链表中的第一个节点就是要删的节点,头删法(不带头结点的单链表)
if(pr == NULL)
{
hash ->hashTable[pos] = p->next;
free(p);
}
else
{
pr->next = p->next;
free(p);
}
return 1;
}
//销毁
void DestroyHash(HashNode *hash , KeyType , key)
{
if(hash == NULL) exit(0);
for(int i ; i<HASHNUM ; ++i)
{
while(hash->hashTable[i] != NULL)
{
HashNode *p = hash->hashTable[i];
hash->hashTable[i] = p->next;
free(p);
}
}
}