Advertisement
Guest User

linked list

a guest
Mar 24th, 2015
2,616
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.71 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <ctype.h>
  5.  
  6. typedef struct node //struct for linked list
  7. {
  8. char* word;
  9. struct node* next;
  10. }
  11. node;
  12.  
  13. int findhash(char firstletter) //this function returns a hash value for first alphabet of every word
  14. {
  15. int hash = 0;
  16.  
  17. if(isupper(firstletter))
  18. hash = firstletter-'A';
  19. else hash = firstletter-'a';
  20.  
  21. return hash;
  22. }
  23.  
  24. void init_table(node* hashtable[])
  25. {
  26. for(int i = 0; i < 26; i++)
  27. hashtable[i] = NULL;
  28. }
  29.  
  30. int main (void)
  31. {
  32. char* dictfile = "small";
  33.  
  34. FILE* dict = fopen(dictfile, "r");
  35.  
  36. if (dict == NULL)
  37. return 1;
  38.  
  39. char oneword[47]; //to store the word from fscanf()
  40.  
  41. node* hashtable [26]; //1. creates a hashtable
  42.  
  43. init_table(hashtable); //1. initialize hashtable to NULL
  44.  
  45. while ((fscanf (dict, "%s", oneword)) > 0) //2.While (true)
  46. {
  47. node* temp = malloc(sizeof(node)); //3. Create a node pointer temp and allocate memory for it
  48. temp->word = malloc(strlen(oneword)+1); //new!
  49. strcpy(temp->word, oneword); //improvement by eliminating use of char* firstword
  50.  
  51. int hash = findhash(temp->word[0]); //returns an index for the first alphabet of the word
  52.  
  53. //printf("%s\n", temp->word); //prints the value (just for debug)
  54.  
  55. temp->next = hashtable[hash];
  56. hashtable[hash] = temp;
  57. }
  58.  
  59. for (int i = 0; i < 26; i++)
  60. {
  61. node* traverse = hashtable[i];
  62.  
  63. while (traverse != NULL) //loop to print the linked list
  64. {
  65. if (traverse->word > 0)
  66. printf("%s\n", traverse->word);
  67.  
  68. traverse = traverse->next;
  69. }
  70. }
  71.  
  72. for (size_t i=0; i<26; ++i) //free all memory
  73. {
  74. while (hashtable[i])
  75. {
  76. node *temp = hashtable[i];
  77. hashtable[i] = temp->next;
  78. free(temp->word);
  79. free(temp);
  80. }
  81. }
  82.  
  83. printf("\n");
  84.  
  85. fclose(dict);
  86.  
  87. printf("SUCCESS!!\n");
  88.  
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement