高手帮忙看看我写的哈希函数为什么不对,多谢!!!
#include <stdio.h>
#include <malloc.h>
#include <fatal.h>
#ifndef _HashSep_H_
#define MinTableSize 128129
typedef char *ElementType; //自定义Key数据类型
struct ListNode; //节点的结构体
typedef struct ListNode *Position; //指向节点的指针
typedef Position List; //指向头节点的指针
struct HashTbl; //哈希表的结构体
typedef struct HashTbl *HashTable;
HashTable InitializeTable(long TableSize); //基本函数声明
void DestroyTable(HashTable H);
Position Find(ElementType Key,HashTable H);
void Insert(ElementType Key,HashTable H);
ElementType Retrieve(Position P);
#endif
////////////////////////////////////////////具体的结构体定义
struct ListNode{
ElementType Element;
Position Next;
};
struct HashTbl{
long TableSize;
List *TheLists;
};
////////////////////////////////////////////////////////函数定义
long IndexHash(unsigned char *Key,long TableSize){
unsigned long HashVal;
HashVal=(*Key)*1000+*(Key+1);
return HashVal%TableSize;
}
HashTable InitializeTable(long TableSize){
HashTable H;
long i;
if(TableSize <MinTableSize){
Error( "TableSize is too small ");
return NULL;
}
H=malloc( sizeof( struct HashTbl) );
if( H==NULL )
FatalError( "out of space!!! ");
//H-> TableSize=NextPrime(TableSize); //求大于TableSize的最小素数
H-> TheLists=malloc( sizeof(List)*H-> TableSize );
if(H-> TheLists==NULL)
FatalError( "TheLists ");
for(i=0;i <H-> TableSize;i++){
H-> TheLists[i]=malloc( sizeof(struct ListNode) );
if(H-> TheLists[i]==NULL)
FatalError( "fuck ");
else
H-> TheLists[i]-> Next=NULL;
}
return H;
}
Position Find(ElementType Key,HashTable H){
Position P;
List L; //这里List和Position好像没什么区别
L=H-> TheLists[IndexHash(Key,H-> TableSize)];
P=L-> Next;
while(P!=NULL && P-> Element!=Key )
P=P-> Next;
return P;
}
void Insert(ElementType Key,HashTable H){
Position Pos,NewCell;
List L; //L是头节点
Pos=Find(Key,H);
if(Pos==NULL ){
NewCell=malloc(sizeof(struct ListNode) );
if(NewCell==NULL)
FatalError( "为新节点分配空间失败 ");
else{
L=H-> TheLists[IndexHash( Key,H-> TableSize ) ];
NewCell-> Next=L-> Next;
L-> Next=NewCell;
NewCell-> Element=Key;
}
}
}
////////////////////////////////////////////main()函数
main(){
long a,b;
unsigned char Buffer[32],*p;
HashTable H;
FILE *Dictionary;
Dictionary=fopen( "dictionary.txt ", "r ");
H=InitializeTable(128128);
getchar();
}
[解决办法]
#define MinTableSize 128129
if(TableSize <MinTableSize){
Error( "TableSize is too small ");
return NULL;
}
H=InitializeTable(128128);
是不是这个问题?