构造哈希函数的方法选择:除留余数法
由经验得知∶一般情况下,可以选p为质数或不包含小于20的质因数的合数
处理哈希冲突的方法:链地址法
哈希表(除留余数+链地址法)代码
#include<stdio.h>
#include<assert.h>
#include<malloc.h>
#define m 13
typedef struct DataType
{
int key;
//InfoType otherinfo;
}DataType;
typedef struct Node
{
DataType data;
struct Node* next;
}Node;
typedef struct
{
Node* next;
}HashTable[m];
//初始化
void InitHash(HashTable ht)
{
assert(ht != NULL);
if (ht == NULL)
{
return;
}
for (int i = 0; i < m; i++)
{
ht[i].next = NULL;
}
}
static int H(int key)
{
return key % m;
}
Node* Search(const HashTable ht, int key)
{
int hi = H(key);
for (Node* p = ht[hi].next; p != NULL; p = p->next)
{
if (p->data.key == key)
return p;
}
//for (int i = 0; i < m; i++)
//{
// if (ht[i].next != NULL)
// {
// for (Node* p = ht->next; p != NULL; p = p->next)
// {
// if (p->data.key == key)
// return p;
// }
// }
//}
return NULL;
}
bool Insert(HashTable ht, int key)
{
int hi = H(key);
if (Search(ht, key) != NULL)
{
return false;
}
Node* p = (Node*)malloc(sizeof(Node));
assert(p != NULL);
p->data.key = key;
//头插
p->next = ht[hi].next;
ht[hi].next = p;
return true;
}
void Show(HashTable ht)
{
for (int i = 0; i < m; i++)
{
printf("哈希表值为%d的有", i);
for (Node* p = ht[i].next; p != NULL; p = p->next)
{
printf("%d ", p->data.key);
}
printf("\n");
}
}
int main()
{
HashTable ht;
InitHash(ht);
int arr[16] = { 13,5,7,1,2,9,28,25,6,11,10,15,17,23,34,19 };
for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++)
{
Insert(ht, arr[i]);
}
Show(ht);
return 0;
}