头文件
#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW 0
#define SUCCESS 1
#define UNSUCCESS 0
#define DUPLICATE -1
结构体
typedef int KeyType;
typedef struct{
KeyType key;
} RcdType;
typedef int Status;
typedef struct {
RcdType *rcd;
int size;
int count;
int *tag;
int (* hash)(KeyType Key, int hashSize);
void (* collision)(int & hashValue,int hashSize);
}HashTable;
哈希函数
int Hash (KeyType Key,int hashSize){
return (3*Key)%hashSize;
}
冲突函数
void Collision(int &hashValue,int hashSize){
hashValue = (hashValue+1)%hashSize;
}
初始化
Status InitHash(HashTable &H, int size, int(*hash)(KeyType,int), void(*collision)(int &,int)){
int i;
H.rcd = (RcdType *)malloc(size * sizeof(RcdType));
H.tag = (int *)malloc(size * sizeof(int));
if(NULL==H.rcd||NULL==H.tag)
return OVERFLOW;
for(i =0; i<size; i++)
H.tag[i]=0,H.rcd[i].key=0;
H.size = size;
H.hash = Hash;
H.collision = Collision;
H.count = 0;
return OK;
}
查找
Status SearchHash(HashTable H, KeyType key, int &p, int &c){
p= H.hash(key,H.size);
while (H.tag[p]!=0 && (H.rcd[p].key!=key || H.tag[p]==-1)){
H.collision(p,H.size);
c++;
}
if(H.rcd[p].key==key&&1==H.tag[p])
return SUCCESS;
else
return UNSUCCESS;
}
插入
int InsertHash(HashTable &H,RcdType e){
int c=0,j;
if(SUCCESS == SearchHash(H,e.key,j,c))
return -1;
else{
H.rcd[j] = e;
H.tag[j] = 1;
H.count++;
return c;
}
}
删除
Status DeleteHash(HashTable &H, KeyType key, RcdType &e){
int j,c;
if(UNSUCCESS == SearchHash(H,key,j,c))
return UNSUCCESS;
else{
e= H.rcd[j];
H.tag[j] = -1;
H.count--;
return SUCCESS;
}
}
处理冲突的操作
HashTable rec(HashTable &H, int inc)
{
HashTable new_H;
InitHash(new_H, H.size + inc,*Hash, *Collision);
for (int i = 0; i < H.size; ++i)
{
if (H.tag[i] = 1)
InsertHash(new_H, H.rcd[i]);
}
return new_H;
}
main函数
int main()
{
HashTable H;
InitHash(H, 10,*Hash, *Collision);
for (int i = 1; i <= 30; ++i)
{
RcdType data;
data.key = (rand() + 50) % 50 + 1;
InsertHash(H, data);
int times = 0, p;
SearchHash(H, data.key, p, times);
printf("times = %d\n", times);
for (int i = 0; i < H.size; ++i)
printf("%d ", H.rcd[i].key);
printf("\n");
if (times >= 3 || H.count/H.size > 0.6)
H = rec(H, 5);
}
return 0;
}