C语言用二叉树统计一个源文件(一)

2012-12-17 12:50:44 · 作者: · 浏览: 1371

    由于出现的单词不确定,所以用二叉树实现:

    [cpp]

    //TreeNode.h

    typedef struct _TreeNode

    {

    int count; //出现的次数

    char* word;//单词本省

    struct _TreeNode* left;

    struct _TreeNode* right;

    }TreeNode;

    //给TreeNode分配内存

    TreeNode* talloc(void)

    {

    return (TreeNode*)malloc(sizeof(TreeNode));

    }

    //打印tree

    void tprint(TreeNode* root)

    {

    //打印left->self->right

    if(root!=NULL)

    {

    tprint(root->left);

    printf("%4d %s\n",root->count,root->word);

    tprint(root->right);

    }

    }

    //把单词添加节点的合适位置

    TreeNode* addNode(TreeNode* node,const char* word)

    {

    int con;

    TreeNode* tmp;

    if(node==NULL)

    {

    node = talloc();

    node->count=1;

    node->word=strdup(word);

    node->left=node->right=NULL;

    }else if((con=strcmp(word,node->word))<0)

    {

    tmp = addNode(node->left,word);

    node->left=tmp;

    }else if(con>0)

    {

    tmp = addNode(node->right,word);

    node->right=tmp;

    }else{

    node->count++;

    }

    return node;

    }

    /**

    从指定的流中读取单词

    */

    int getWord(char* ch,size_t n,FILE* f)

    {

    int c;

    char* p = ch;

    while(isspace(c=fgetc(f)))

    ;

    if(c!=EOF)

    *p++=c;

    if(!isalpha(c))

    {

    *p='\0';

    return c;

    }

    for(;--n>0;p++)

    {

    if(!isalpha(*p=fgetc(f)))

    {

    ungetc(*p,f);

    break;

    }

    }

    *p='\0';

    return c;

    }