Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define HASHSIZE 101
- typedef struct{
- char *value;
- int number;
- struct nlist *next;
- }nlist;
- unsigned hash(char *s);
- nlist *lookup(char *s);
- nlist *install(char *s);
- nlist *hashtab[HASHSIZE];
- int main(int argc, char *argv[]){
- char str[50];
- int i = 0;
- nlist *pp;
- FILE *file;
- file = fopen(argv[1], "r");
- if (argc != 2){
- printf("Enter 1 file name.\n");
- return 0;
- }
- if (file == NULL){
- printf("Error!\n");
- return 0;
- }
- while (fscanf(file, "%s", str) != EOF) {
- if ((pp = lookup(str)) == NULL) {
- install(str);
- }
- }
- for (; i < HASHSIZE; i++) {
- if (hashtab[i] != NULL)
- printf("%s - %d times\n", hashtab[i]->value, hashtab[i]->number);
- }
- return 0;
- }
- unsigned hash(char *s){
- unsigned hashval;
- for (hashval = 0; *s != '\0'; s++)
- hashval = *s + 31 * hashval;
- return hashval % HASHSIZE;
- }
- nlist *lookup(char *s){
- nlist *np;
- for (np = hashtab[hash(s)]; np != NULL; np = np->next)
- if (strcmp(s, np->value) == NULL){
- np->number++;
- return np;
- }
- return NULL;
- }
- nlist *install(char *s){
- nlist *np;
- np = (nlist *) malloc(sizeof(*np));
- if (np == NULL || (np->value = strdup(s)) == NULL)
- return NULL;
- np->number = 1;
- np->next = hashtab[hash(s)];
- hashtab[hash(s)] = np;
- return np;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement