二叉树统计单词个数

来源:互联网 发布:nba骑士vs公牛数据 编辑:程序博客网 时间:2024/05/19 23:14
#include <stdio.h>#include <string.h>#include <ctype.h>#include <stdlib.h>#define MAXWORD 1000struct tnode//节点{    char *s;    int count;    struct tnode *left;    struct tnode *right;};struct tnode *addtree(struct tnode *, char *);void treeprint(struct tnode *);int getword(char *, int);void freetree(struct tnode *p);//原文没有这个函数,本来也没写,心疼一下堆栈int main(){    struct tnode *root = NULL;    char word[MAXWORD];    while( getword(word, MAXWORD) != EOF )    {        if(isalpha(word[0]))            root = addtree(root, word);    }    treeprint(root);    freetree(root);    return 0;}void treeprint(struct tnode *t)//递归打印树{    if( t != NULL )    {        treeprint( t->left );        printf("%4d %s\n", t->count, t->s );        treeprint( t->right );    }}struct tnode *talloc(void)//封装malloc{    return (struct tnode *)malloc( sizeof(struct tnode) );}struct tnode *addtree(struct tnode *r, char *s)//递归{    int cond;    if( r == NULL )    {        r = talloc();        r->count = 1;        r->s = strdup(s);        r->left = r->right = NULL;    }    else if( (cond = strcmp(s, r->s)) < 0 )//cond记录比较结果        r->left = addtree( r->left, s );    else if( cond > 0)        r->right = addtree( r->right, s );    else        r->count++;//如果已经存在,计数器自增    return r;}void freetree(struct tnode *p){    if(p != NULL)    {        freetree(p->left);        freetree(p->right);        free(p->s);        free(p);    }}//getch和ungetch的实现,ungetch把没用的已经读入字符//存回缓冲区,用自己定义的栈实现int buf[BUFSIZ];int bp = 0;int getch()//如果栈空了,读入缓冲区的内容{    return bp == 0?getchar():buf[--bp];}void ungetch(int c){    if( bp < BUFSIZ)        buf[bp++] = c;    else        printf("BUF IS FULL\n");}int getword(char *word, int n){    char c, *s = word;    while( isspace( c = getch() ) );    if( c != EOF ) *s++ = c;else return EOF;    if( !isalnum(c) ) { *s = '\0'; return c;}    for(; --n; s++)        if( !isalnum( *s = getch() ) )            {ungetch(*s);break;}    *s = '\0';    return word[0];//判断是否EOF}


来自《c程序设计语言》,有改动。


原创粉丝点击