我在这上面花了几天时间被困住并被搜查。我需要使用 C 创建一个词频程序。为了跟踪冲突,我使用了一个链表,但我的代码没有给出正确的频率(例如,“the”的频率应该是 25,但它是 18)。我究竟做错了什么?。这是我的代码:
void addToArr( char *str, HASH_ARR_ELEM hashArr[]){
int homeAddress = 0;
int addResult = 0;
WORD *tempWord;
homeAddress = hashFunct(str);
if(!(tempWord = (WORD*)malloc(sizeof(WORD))))
printf("Memory Allocation Error\n"),
exit(100);
strcpy(tempWord->str,str);
tempWord->count = 1;
if(hashArr[homeAddress].wordPtr == NULL){
// allocate memory
if(!(hashArr[homeAddress].wordPtr = (WORD*)malloc(sizeof(WORD))))
printf("Memory Allocation Error\n"), exit(100);
strcpy(hashArr[homeAddress].wordPtr->str,tempWord->str);
hashArr[homeAddress].wordPtr->count = 1;
} else if(hashArr[homeAddress].wordPtr != NULL && hashArr[homeAddress].headPtr == NULL){
if(strcmp(hashArr[homeAddress].wordPtr->str,tempWord->str))
hashArr[homeAddress].wordPtr->count++;
else{
hashArr[homeAddress].headPtr = createList(cmpWord);
if(!hashArr[homeAddress].headPtr)
printf("\aCannot create list\n"),
exit(100);
addNode(hashArr[homeAddress].headPtr,tempWord);
}
}else
if(strcmp(hashArr[homeAddress].wordPtr->str,tempWord->str))
hashArr[homeAddress].wordPtr->count++;
else
{
addResult = addNode(hashArr[homeAddress].headPtr,tempWord);
if(addResult != 0)
if(addResult == -1)
printf("Memory Overflow adding node\n"),
exit(120);
else
{
retrieveNode(hashArr[homeAddress].headPtr,tempWord,(void**)&tempWord);
tempWord->count++;
printf("%s %d\n\n", tempWord->str, tempWord->count);
}
}
} // end addToArr