home *** CD-ROM | disk | FTP | other *** search
/ The C Users' Group Library 1994 August / wc-cdrom-cusersgrouplibrary-1994-08.iso / vol_100 / 154_01 / hash.c < prev    next >
Text File  |  1979-12-31  |  1KB  |  61 lines

  1. /* hash.c:    create and display an open hash table */
  2.  
  3. #include <stdio.h>
  4. #define MAXSTR 31
  5. #define PRIME 23
  6.  
  7. struct element {
  8.     struct element *next;
  9.     char *data;
  10. } *hashtab[PRIME];
  11.  
  12. main()
  13. {    int i;
  14.     char s[MAXSTR];
  15.  
  16.     for (i = 0; i < PRIME; ++i)        /* ..initialize bucket.. */
  17.         hashtab[i] = NULL;
  18.     while (gets(s) != NULL)            /* ..create table.. */
  19.         if (search(s) == 0) insert(s);    
  20.     for (i = 0; i < PRIME; ++i) {        /* ..print it out.. */
  21.         printf("%3d: -> ",i);
  22.         print_list(hashtab[i]);
  23.         putchar('\n');
  24.     }
  25. }
  26.  
  27. print_list(p)
  28. struct element *p;
  29. {    for ( ; p != NULL; p = p->next)
  30.         printf("%s -> ",p->data);
  31. }
  32.  
  33. int hashval(s)
  34. char *s;
  35. {    int sum;
  36.     
  37.     for (sum = 0; *s; sum += *s++) ;
  38.     return sum % PRIME;
  39. }
  40.  
  41. insert(s)
  42. char *s;
  43. {    struct element *p;
  44.     int h;
  45.  
  46.     p = (struct element *) malloc(sizeof(struct element));
  47.     p->next = hashtab[h = hashval(s)];
  48.     hashtab[h] = p;            /* insert at top (why not?) */
  49.     p->data = (char *) malloc(strlen(s)+1);
  50.     strcpy(p->data,s);
  51. }
  52.  
  53. int search(s)
  54. char *s;
  55. {    struct element *p;
  56.  
  57.     for(p = hashtab[hashval(s)]; p != NULL; p = p->next)
  58.         if (strcmp(p->data,s) == 0) return 1;
  59.     return 0;
  60. }
  61.