acobzew

sem5-problem2

May 9th, 2017
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.55 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <ctype.h>
  5.  
  6. #define MAX_WORD_LEN 100
  7. #define HASH_SIZE 101
  8.  
  9. struct nlist {
  10.     struct nlist *next;
  11.     char *word;
  12.     int count;
  13. };
  14.  
  15. static struct nlist *hashTable[HASH_SIZE];
  16.  
  17. unsigned hash(char *s) {
  18.     unsigned hashval;
  19.     for (hashval = 0; *s != '\0'; s++)
  20.         hashval = *s + 31 * hashval;
  21.     return hashval % HASH_SIZE;
  22. }
  23.  
  24. struct nlist *search(char *s) {
  25.     struct nlist *np;
  26.     for (np = hashTable[hash(s)]; np != NULL; np = np->next)
  27.         if (strcmp(s, np->word) == 0)
  28.             return np;
  29.     return NULL;
  30. }
  31.  
  32. struct nlist *add(char *word) {
  33.     struct nlist *np;
  34.     unsigned hashval;
  35.     if ((np = search(word)) == NULL) {
  36.         np = (struct nlist *) malloc(sizeof(*np));
  37.         if (np == NULL || (np->word = strdup(word)) == NULL)
  38.             return NULL;
  39.         hashval = hash(word);
  40.         np->count = 1;
  41.         np->next = hashTable[hashval];
  42.         hashTable[hashval] = np;
  43.     }
  44.     else
  45.         np->count++;
  46.     return np;
  47. }
  48.  
  49. int main()
  50. {
  51.     int i;
  52.     for (i = 0; i < HASH_SIZE; i++)
  53.         hashTable[i] = NULL;
  54.     char fileword[100];
  55.     printf("Enter file name: ");
  56.     scanf("%s", fileword);
  57.     FILE *f = fopen(fileword, "r");
  58.  
  59.     char word[MAX_WORD_LEN], c;
  60.     i = 0;
  61.     do
  62.     {
  63.         c = fgetc(f);
  64.         if (isalpha(c) || isdigit(c))
  65.             word[i++] = c;
  66.         else if (i != 0)
  67.         {
  68.             word[i] = '\0';
  69.             i = 0;
  70.             add(word);
  71.         }
  72.     }
  73.     while (c != EOF);
  74.  
  75.     struct nlist *np;
  76.     for (i = 0; i < HASH_SIZE; i++)
  77.     {
  78.         np = hashTable[i];
  79.         while (np != NULL)
  80.         {
  81.             printf("%5d\t%s\n", np->count, np->word);
  82.             np = np->next;
  83.         }
  84.     }
  85.  
  86.     fclose(f);
  87.     return 0;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment