由於出現的單詞不確定,所以用二叉樹實現:
[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;
}
//是否tree占用的內存
void treeFree(TreeNode* root)
{
if(root!=NULL)
{
treeFree(root->left);
free(root->word); //釋放節點的word占用的內存
free(root); //是否節點占用的內存
treeFree(root->right);
}
}
//Test.c
#include <stdio.h>
#include <stdlib.h>
#include "TreeNode.h"
#define MAX 100
int main(int argc, char *argv[])
{
FILE* f;
char w[MAX]={0};
char* fname="TreeNode.h";
if((f=fopen(fname,"r"))!=NULL)
{
TreeNode* root = NULL;
while((getWord(w,MAX,f)!=EOF))
{
if(isalpha(w[0]))
root = addNode(root,w);
}
tprint(root);
treeFree(root);
fclose(f);
}else{
printf("open %s error\n",fname);
}
getchar();
return 0;
}