#include<stdio.h>#include<stdlib.h>#include<conio.h>typedefint KeyType;typedefstruct{
KeyType key;//冲突次数int hi;} DataType;typedefstruct{
DataType *data;//hash表的长度int tableSize;//表中关键字个数int curSize;} HashTable;/*创建hash表*/voidCreateHashTable(HashTable *h,int m,int p,int hash[],int n){int i, sum, addr, di, k =1;(*h).data =(DataType *)malloc(m *sizeof(DataType));if(!(*h).data){exit(-1);}//初始化hash表for(i =0; i < m; i++){(*h).data[i].key =-1;(*h).data[i].hi =0;}//求hash地址,并处理冲突for(i =0; i < n; i++){
sum =0;
addr = hash[i]% p;
di = addr;if((*h).data[addr].key ==-1){//如果不冲突,将元素存储在表中(*h).data[addr].key = hash[i];(*h).data[addr].hi =1;}else{//用线性探测再散列处理冲突do{
di =(di + k)% m;
sum +=1;}while((*h).data[di].key !=-1);(*h).data[di].key = hash[i];(*h).data[di].hi = sum +1;}}//hash表中关键字个数(*h).curSize = n;//hash表长度(*h).tableSize = m;}/*在hash表中查找关键字K的元素*/intSearchHash(HashTable h, KeyType k){int d, d1, m;
m = h.tableSize;//求k的hash地址
d = d1 = k % m;while(h.data[d].key !=-1){if(h.data[d].key == k){return d;}else{
d =(d +1)% m;}if(d == d1){return0;}}return0;}/*求hash表的平均查找长度*/voidHashASL(HashTable h,int m){float average =0;int i;for(i =0; i < m; i++){
average = average + h.data[i].hi;}
average = average / h.curSize;printf("\n平均查找长度ASL=%2.f", average);printf("\n");}/*输出hash表*/voidDisplayHash(HashTable h,int m){int i;printf("hash表地址:");for(i =0; i < m; i++){printf("%-5d", i);}printf("\n关键字key:");for(i =0; i < m; i++){printf("%-5d", h.data[i].key);}printf("\n冲突次数:");for(i =0; i < m; i++){printf("%-5d", h.data[i].hi);}printf("\n");}intmain(void){int hash[]={78,90,66,70,155,82,123,231};int m =11, p =11, n =8, pos;
KeyType k;
HashTable h;CreateHashTable(&h, m, p, hash, n);DisplayHash(h, m);
k =155;
pos =SearchHash(h, k);printf("关键字%d在hash表中的位置为:%d\n", k, pos);HashASL(h, m);getch();printf("\n");system("pause");return0;}