Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- #include <ctype.h>
- #define MAX_WORD_LEN 100
- #define HASH_SIZE 101
- struct nlist {
- struct nlist *next;
- char *word;
- int count;
- };
- static struct nlist *hashTable[HASH_SIZE];
- unsigned hash(char *s) {
- unsigned hashval;
- for (hashval = 0; *s != '\0'; s++)
- hashval = *s + 31 * hashval;
- return hashval % HASH_SIZE;
- }
- struct nlist *search(char *s) {
- struct nlist *np;
- for (np = hashTable[hash(s)]; np != NULL; np = np->next)
- if (strcmp(s, np->word) == 0)
- return np;
- return NULL;
- }
- struct nlist *add(char *word) {
- struct nlist *np;
- unsigned hashval;
- if ((np = search(word)) == NULL) {
- np = (struct nlist *) malloc(sizeof(*np));
- if (np == NULL || (np->word = strdup(word)) == NULL)
- return NULL;
- hashval = hash(word);
- np->count = 1;
- np->next = hashTable[hashval];
- hashTable[hashval] = np;
- }
- else
- np->count++;
- return np;
- }
- int main()
- {
- int i;
- for (i = 0; i < HASH_SIZE; i++)
- hashTable[i] = NULL;
- char fileword[100];
- printf("Enter file name: ");
- scanf("%s", fileword);
- FILE *f = fopen(fileword, "r");
- char word[MAX_WORD_LEN], c;
- i = 0;
- do
- {
- c = fgetc(f);
- if (isalpha(c) || isdigit(c))
- word[i++] = c;
- else if (i != 0)
- {
- word[i] = '\0';
- i = 0;
- add(word);
- }
- }
- while (c != EOF);
- struct nlist *np;
- for (i = 0; i < HASH_SIZE; i++)
- {
- np = hashTable[i];
- while (np != NULL)
- {
- printf("%5d\t%s\n", np->count, np->word);
- np = np->next;
- }
- }
- fclose(f);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment