/*
*这个函数实现散列的基本操作,使用开放地址法解决哈希冲突
*(C) 2010/9/21
*/
#include<stdio.h>
#define Maxsize 100
#define NULLKEY -1
#define DELKEY -2
typedef struct //定义哈希表结构
{
int key;
int count;
}HashTable;
int SearchHT(HashTable ha[], int p, int k)//在哈希表中查找
{
int i = 0, adr;
adr = k % p;
while(ha[adr].key != NULLKEY && ha[adr].key != k){
i++;
adr = (adr + 1) % p;
}
if(ha[adr].key == k)
return adr;
else
return -1;
}
int DeleteHT(HashTable ha[], int p, int k, int number)//删除一个元素
{
int adr;
adr = SearchHT(ha, p, k);
if(adr != -1){
ha[adr].key = DELKEY;
number--;
return 1;
}
else
return 0;
}
void InsertHT(HashTable ha[], int k, int p)//元素插入
{
int i, adr;
adr = k % p;
if(ha[adr].key == NULLKEY || ha[adr].key == DELKEY){
ha[adr].key = k;
ha[adr].count = 1;
}
else{
i = 1;
do{
adr = (adr + 1) % p;
i++;
}while(ha[adr].key != NULLKEY && ha[adr].key != DELKEY);
ha[adr].key = k;
ha[adr].count = i;
}
}
void CreateHT(HashTable ha[], int x[], int n, int m, int p)//建立哈希表
{
int i;
for(i = 0;i < m ;i++){
ha[i].key = NULLKEY;
ha[i].count = 0;
}
for(i = 0;i < n;i++)
InsertHT(ha, x[i], p);
}
int main(void)
{
int i;
HashTable ha[13];
int HT[11] = {16, 74, 60, 43, 54, 90, 46, 31, 29, 88, 77};
CreateHT(ha , HT , 11, 13, 13);//创建Hash表
for(i = 0;i < 13; i++)
printf("key:%d\tcount:%d\t\n", ha[i].key, ha[i].count);
return 0;
}
|