读书人

高手帮忙看看小弟我写的哈希函数为什么

发布时间: 2012-02-02 23:57:14 作者: rapoo

高手帮忙看看我写的哈希函数为什么不对,多谢!!!
一用Insert()函数往里面插入元素,就报错,ft!

#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

H=InitializeTable(128128);

在这个地方返回了
if(TableSize <MinTableSize){
//Error( "TableSize is too small ");
return NULL;
}

这时根本就没有申请到空间,你这样写时
L=H-> TheLists[IndexHash((unsigned char *)Key,H-> TableSize)];
就出错了。

顺便提一下,看你的程序很费劲,主要是typedef;还有强制转换类型的地方都没有转。
思路是对的,看来主要是指针的检查不够。

读书人网 >C语言

热点推荐