/* wordfreq.c; cpl6.5 */ #include #include #include /* for malloc() */ #define MAXWORD 100 struct tnode { /* the tree node */ char *word; /* points to the word */ short count; /* number of occurrences */ struct tnode *left; /* left branch */ struct tnode *right;/* right branch */ }; struct tnode *addtree(struct tnode *, char *); void treeprint(struct tnode *); struct tnode *talloc(void); char *strdup(char *); int getword(char *, int); void error(char *); /* word frequency count */ main() { struct tnode *root; char word[MAXWORD]; root = NULL; while (getword(word, MAXWORD) != EOF) if (isalpha(word[0])) root = addtree(root,word); treeprint(root); return 0; } /* addtree: add a node with w, at or below p */ struct tnode *addtree(struct tnode *p, char *w) { int cond; if (p == NULL) { /* a new word has arrived */ p = talloc(); /* make a new node */ if (p == NULL) error("addtree: memory allocation failure"); p->word = strdup(w);/* copy new word to its own memory location */ p->count = 1; /* initialize count for new word */ p->left = p->right = NULL; /* new branches empty */ } else if ((cond = strcmp(w, p->word)) == 0) p->count++; /* repeated word */ else if (cond < 0) /* into left branch */ p->left = addtree(p->left, w); else p->right = addtree(p->right, w); return p; } /* treeprint: in-order print of tree p */ void treeprint(struct tnode *p) { if (p != NULL) { treeprint(p->left); printf("%4d %s\n", p->count, p->word); treeprint(p->right); } } /* talloc: make a tnode */ struct tnode *talloc(void) { return (struct tnode *) malloc(sizeof(struct tnode)); } char *strdup(char *s) /* make a duplicate of s */ { char *p; p = (char *) malloc(strlen(s) + 1); /* +1 for '\0' */ if (p != NULL) strcpy(p, s); else error("strdup: memory allocation failure"); return p; } /* getword: get next word or character from input */ int getword(char *word, int lim) { int c; char *w = word; while (isspace(c = getchar())) ; if (c != EOF) *w++ = c; if (!isalpha(c)) { *w = '\0'; return c; } for ( ; --lim > 0; w++) if (!isalnum(*w = getchar())) { ungetc(*w, stdin); break; } *w = '\0'; return word[0]; } void error(char *s) { printf("\n%s\n"); exit(1); }