我正在做一个将字典单词插入哈希表的项目。如果发生冲突,则将新单词散列到下一个相同的位置。我创建了一个指针数组:
typedef struct WordNode * WordNodeP;
typedef struct WordNode
{
char word[WORDSIZE];
struct WordNodeP *next;
}WordNodeT;
WordNodeP table[TABLESIZE];
我通过以下函数将字典中的每个单词散列到数组的指针中:
散列函数:
int hashFunction(char word[]) //This function takes a string of word and break down each letter
{ //to integer value and use hash function. Then sum up all the values.
int i = 0;
int sum = 0;
while(word[i]!='\0'){
if((int)word[i] < 97) //If the ASC value of the letter is less than 97. It means it is a cap letter
sum+= 3*(i+1)*(i+1)*(word[i]+32);
else
sum+= 3*(i+1)*(i+1)*word[i];
i++;
}
if(sum > TABLESIZE) //TABLESIZE = 12001;
sum = sum % TABLESIZE;
return sum;
}
addWord:
void addWord(int val,char word[]) //This function adds words to specific index of array of LinkedList
{
if(table[val]!=NULL){ //If the position is occupied
WordNodeT *temp = createNewNode(word);
temp->next = table[val]->next;
table[val]->next = temp;
}
//printf("%s",table[val]->word);
//printf("%s\n",table[val]->word);
else
table[val] = createNewNode(word); //hash in the word to the table
}
CreateNewNode:
WordNodeP createNewNode(char word[])
{
WordNodeT* newNode = (WordNodeT*)malloc(sizeof(WordNodeT));
strcpy(newNode->word,word);
//printf("%s", newNode->word);
newNode->next = NULL;
return newNode;
}
问题在于查找功能。无论传入哪个单词,它总是返回0(未找到);
查找
int lookup(char * word) //see if word exists in the dictionary
{
int val;
val = hashFunction(word);
printf("hash value is %d\n",val);
WordNodeT *temp = table[val];
while(temp!=NULL){ //all the way through
if(strcmp(temp->word,word)== 0){
return 1;
}
temp = temp->next;
}
return 0;
}
请注意,我把
printf("hash value is %d\n",val)
在查找hashValue中查找。
主要是我代码:
printf("%d\n",lookup("hello"));
对于输出,我得到了5848的hashValue和0的返回值。 因为我的返回值为0,所以我编码用于检查目的:
WordNodeT *temp = table[5948];
while (temp->word!=NULL){
printf("%s",temp->word);
temp = temp->next;
}
打印出其他单词,其中一个是“扇贝”,我计算了它的hashValue,“扇贝”的hashValue :((1 ^ 2 * 3 * 115)+(2 ^ 2 * 3 * 99)+ (3 ^ 2 * 3 * 97)+(4 ^ 2 * 3 * 108)+(5 ^ 2 * 3 * 108)+(6 ^ 2 * 3 * 111)+(7 ^ 2 * 3 * 112)) %TABLESIZE(12001)= 9885;
那么你们可以帮助我吗?