Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <ctype.h>
- typedef struct node //struct for linked list
- {
- char* word;
- struct node* next;
- }
- node;
- int findhash(char firstletter) //this function returns a hash value for first alphabet of every word
- {
- int hash = 0;
- if(isupper(firstletter))
- hash = firstletter-'A';
- else hash = firstletter-'a';
- return hash;
- }
- void init_table(node* hashtable[])
- {
- for(int i = 0; i < 26; i++)
- hashtable[i] = NULL;
- }
- int main (void)
- {
- char* dictfile = "small";
- FILE* dict = fopen(dictfile, "r");
- if (dict == NULL)
- return 1;
- char oneword[47]; //to store the word from fscanf()
- node* hashtable [26]; //1. creates a hashtable
- init_table(hashtable); //1. initialize hashtable to NULL
- while ((fscanf (dict, "%s", oneword)) > 0) //2.While (true)
- {
- node* temp = malloc(sizeof(node)); //3. Create a node pointer temp and allocate memory for it
- temp->word = malloc(strlen(oneword)+1); //new!
- strcpy(temp->word, oneword); //improvement by eliminating use of char* firstword
- int hash = findhash(temp->word[0]); //returns an index for the first alphabet of the word
- //printf("%s\n", temp->word); //prints the value (just for debug)
- temp->next = hashtable[hash];
- hashtable[hash] = temp;
- }
- for (int i = 0; i < 26; i++)
- {
- node* traverse = hashtable[i];
- while (traverse != NULL) //loop to print the linked list
- {
- if (traverse->word > 0)
- printf("%s\n", traverse->word);
- traverse = traverse->next;
- }
- }
- for (size_t i=0; i<26; ++i) //free all memory
- {
- while (hashtable[i])
- {
- node *temp = hashtable[i];
- hashtable[i] = temp->next;
- free(temp->word);
- free(temp);
- }
- }
- printf("\n");
- fclose(dict);
- printf("SUCCESS!!\n");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement