Advertisement
Extremum

Untitled

Jun 8th, 2017
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.53 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #define HASHSIZE 101
  5.  
  6. typedef struct{
  7.     char *value;
  8.     int number;
  9.     struct nlist *next;
  10. }nlist;
  11.  
  12. unsigned hash(char *s);
  13. nlist *lookup(char *s);
  14. nlist *install(char *s);
  15.  
  16. nlist *hashtab[HASHSIZE];
  17.  
  18. int main(int argc, char *argv[]){
  19.     char str[50];
  20.     int i = 0;
  21.     nlist *pp;
  22.     FILE *file;
  23.     file = fopen(argv[1], "r");
  24.     if (argc != 2){
  25.         printf("Enter 1 file name.\n");
  26.         return 0;
  27.     }
  28.     if (file == NULL){
  29.         printf("Error!\n");
  30.         return 0;
  31.     }
  32.     while (fscanf(file, "%s", str) != EOF) {
  33.             if ((pp = lookup(str)) == NULL) {
  34.                 install(str);
  35.             }
  36.         }
  37.     for (; i < HASHSIZE; i++) {
  38.         if (hashtab[i] != NULL)
  39.             printf("%s - %d times\n", hashtab[i]->value, hashtab[i]->number);
  40.     }
  41.     return 0;
  42. }
  43.  
  44. unsigned hash(char *s){
  45.     unsigned hashval;
  46.     for (hashval = 0; *s != '\0'; s++)
  47.         hashval = *s + 31 * hashval;
  48.     return hashval % HASHSIZE;
  49. }
  50.  
  51. nlist *lookup(char *s){
  52.     nlist *np;
  53.     for (np = hashtab[hash(s)]; np != NULL; np = np->next)
  54.         if (strcmp(s, np->value) == NULL){
  55.             np->number++;
  56.             return np;
  57.         }
  58.     return NULL;
  59. }
  60.  
  61. nlist *install(char *s){
  62.     nlist *np;
  63.     np = (nlist *) malloc(sizeof(*np));
  64.     if (np == NULL || (np->value = strdup(s)) == NULL)
  65.         return NULL;
  66.     np->number = 1;
  67.     np->next = hashtab[hash(s)];
  68.     hashtab[hash(s)] = np;
  69.     return np;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement