vip% cat tree.c #include #include #include #include #define MAXWORD 100 struct tnode { char *word; int count; struct tnode *left; struct tnode *right; }; struct tnode *addtree(struct tnode *, char *); void treeprint(struct tnode *); struct tnode *talloc(void); int getword(char *, int); char *strdupl(char *); /* word frequency count */ void main(void) { struct tnode *root; char word[MAXWORD]; root = NULL; while (getword(word, MAXWORD) != EOF) if (isalpha(word[0])) root = addtree(root, word); treeprint(root); exit(0); } /* addtree: add a node with w, at or below p */ struct tnode *addtree(struct tnode *p, char *w) { int cond; if (p == NULL) { p = talloc(); p -> word = strdupl(w); p -> count = 1; p -> left = p -> right = NULL; } else if ((cond = strcmp(w, p -> word)) == 0) (p -> count)++; else if (cond < 0) 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)); } /* getword: get next word or charcter 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 (!isalpha(*w = getchar())) { ungetc(*w, stdin); break; } *w = '\0'; return word[0]; } /* strdupl: make duplicate of s.(strdup builtin) */ char *strdupl(char *s) { char *p; p = (char *) malloc(strlen(s)+1); if (p != NULL) strcpy(p, s); return p; } vip% lint -m -u tree.c function returns value which is always ignored strcpy printf ungetc vip% cc -o tree tree.c vip% tree