2017-02-21 1 views
-1

Meine Aufgabe ist es, ein Programm zu implementieren, das ein Wörterbuch in eine Datenstruktur einbindet und eine Rechtschreibprüfung durchführt. Ich habe es geschafft, es mit einer einfachen verknüpften Liste zu tun, aber ich bekomme falsche Ergebnisse, wenn ich versuche, eine Hashtabelle zu verwenden. Ich komme zu vielen falsch geschriebenen Wörtern. Ich habe keine Ahnung, was falsch ist.CS50 pset5 hashtable check issue

typedef struct node 
{ 
char word[LENGTH+1]; 
struct node *next; 
} 
node; 
node *hashtable[150000] = {NULL}; 

die Prüffunktion:

int i = hash(word); 
node *cursor = hashtable[i]; 

while(cursor!=NULL) 
{ 
    if(strcasecmp(cursor->word, word) == 0) 
    { 
     return true; 
    } 
    else 
    { 
     cursor = cursor->next; 
    } 
} 
return false; 

Ich habe versucht Einstellung w-> neben NULL, und es machte absolut keinen Unterschied. Also habe ich es losgeworden.

Die Last in hashtable

// open dictionary file and ensure it worked 
FILE *d = fopen(dictionary, "r"); 
if(d==NULL) 
{ 
    printf("File wont open"); 
    return false; 
}; 


// initiate loop for putting all words into array, untile the end of dictionary. 
while(fscanf(d, "%s", word) != EOF) 
{ 
    //create a new node and ensure it worked 
    node *w = malloc(sizeof(node)); 
    if(w ==NULL) 
    { 
     unload(); 
     return false; 
    } 

    //coppy word from dictionary to node. w->word is a pointer to char in a node created above. 
    strcpy(w->word, word); 

    //get hash code and stor in i. 
    long i = hash(word); 


    //place the node in hashtable in correct place. 
    if(hashtable[i]->next==NULL) 
    { 
     hashtable[i]->next = w; 
    } 
    else 
    { 
     w->next = hashtable[i]->next; 
     hashtable[i]->next = w; 
    } 
} 
fclose(d); 
return true; 

Und eine Hashfunktion:

long hash = 0; 

    for (int counter = 0; str[counter]!='\0'; counter++) 
    { 
     hash = (str[counter] + (hash << 6) + (hash << 16) - hash)%150000;//150000=size of hashtable 
    } 
    return hash; 
+3

Wie sieht ein 'node' aus und wie initialisiert man seine Mitglieder? Nach 'malloc' gibt es keine Garantie, dass' w-> next' zum Beispiel 'NULL' ist. Und ist "w-> word" ein Zeiger oder ein "char" -Array? Sie können die Frage bearbeiten, um weitere Informationen hinzuzufügen. –

Antwort

0

Es stellte sich heraus, dass strcasecmp in Prüffunktion war Groß- und Kleinschreibung. Nach this site sollte es nicht sein.

Nachdem ich alle Zeichen in dem zu überprüfenden Wort manuell in Kleinbuchstaben geändert habe, funktioniert alles wie es sollte.