#include <stdio.h>
#include <stdlib.h>
#define HASHSIZE 12 //set hash p
#define NULLKEY -1000000 //set a impossible key
//如果哈希表中有相同值,该算法找不到第二个该值,需要优化find函数
typedef struct LTable{
int id;//原数组id
int elem;
struct LTable* next;
}LTable;
typedef struct{
LTable elements[HASHSIZE];
int HashP;
}HashTable;
HashTable initHash(int* test,int size){
HashTable h;
int i;
// int test[]={25,13,1,37,5};
LTable *head[HASHSIZE],*node[HASHSIZE],*end[HASHSIZE];
//init HashTable
for (i=0;i<HASHSIZE;i++){
(h.elements[i]).next = NULL;
(h.elements[i]).elem = NULLKEY;
head[i] = &(h.elements[i]);
end[i] = head[i];
}
//将数组里的值放入哈希表
for (i=0;i<size;i++){
if ((h.elements[test[i]%HASHSIZE]).elem == NULLKEY){
(h.elements[test[i]%HASHSIZE]).elem = test[i];
(h.elements[test[i]%HASHSIZE]).id = i;
}
else{
node[test[i]%HASHSIZE] = (LTable*)malloc(sizeof(LTable));
node[test[i]%HASHSIZE]->elem = test[i];
node[test[i]%HASHSIZE]->id = i;
end[test[i]%HASHSIZE]->next = node[test[i]%HASHSIZE];
end[test[i]%HASHSIZE] = node[test[i]%HASHSIZE];
end[test[i]%HASHSIZE]->next = NULL;
}
}
return h;
}
int findHash(int f,HashTable h){
int i,re;
LTable* head[HASHSIZE];
re = f%HASHSIZE;
for (i=0;i<HASHSIZE;i++){
head[i] = &(h.elements[i]);
}
while(head[re]){
if (head[re]->elem == f){
return head[re]->id;
}
head[re] = head[re]->next;
}
return -1;
}
void printHashTable(HashTable h){
int i,k;
LTable* head[HASHSIZE];
for (i=0;i<HASHSIZE;i++){
head[i] = &(h.elements[i]);
}
for (k=0;k<12;k++){
while(head[k]){
printf("%d(arrayID:%d)->",head[k]->elem,head[k]->id);
head[k]=head[k]->next;
}
printf("\n");
}
}
int main(int argc, char *argv[]){
HashTable h;
int i,j=0,k,re;
int test[]={1,2,3,4,5,6,7,8,9,10,11,12,25,13,37,14,15};
h = initHash(test,17);
re = findHash(37,h);
printf("array:");
for (i=0;i<17;i++){
printf("%d ",test[i]);
}
printf("\ntarget:37,find result id:%d\n",re);
//打印到控制台
printHashTable(h);
}
该代码存在的问题:
(1)只支持正整数存储;
(2)当有相同的数存入哈希表,使用findHash函数查找该数时,只能查找链表里第一个数;
(3)对于每个索引内的链表,采取遍历的方式查找。
解决方案:
(1)对所有的数先取绝对值,再取余,负数与正数一样存在链表内;
(2)findHash函数返回值从int类型变为int*类型,查找时把索引下的链表遍历,将所有相同值的ID存为数组返回;
(3)优化findHash查找算法;
存在的问题有缘人来做吧