[说明]
本程序实现对指定文件内的单词进行计数。其中使用二叉树结构来保存已经读入的不同单词,并对相同单词出现的次数进行计数。此二叉树的左孩子结点的字符串值小于父结点的字符串值,右孩子结点的字符串值大于父结点的字符串值。函数getword(char *filename,char*word)是从指定的文件中得到单词。char* strdup(char* s)是复制s所指向的字符串,并返回复制字符串的地址。
[函数]
#include <stdio. h>
#include<ctype. h>
#include <string.h>
#define MAXWORD 100
struct node
char *word;
int count;
struct node *left;
struct node *right;
struct node *addtree(struct node *p,char *w)
int cond;
if (p==NULL) /*向树中插入结点*/
p=(struct node*) malloc(sizeof(struct node));
p->word=strdup (w);
p->count=1;
(1) ;
else if((cond=strcmp (w,p->word))==0) (2) ;
else if (cond<0) p->left= (3) ;
else p->right= (4) ;
return p;
main()
struct node *root;
char word [MAXWORD];
root=NULL;
filename="example .dat";
while getword(filename,word)! =EOF
root= (5) ;
参考答案:adtree(root,word)
解析: 在用二叉树结构来保存指定文件内的单词时,采用递归调用。首先在树中创建一个结点,因此空(1)填p->left=p->right=NULL。如果要插入的字符串已经存在,则计数值加一,即空(2)填p->count++;如果要插入的字符串小于此结点上字符串的值,则再次调用此函数,即空(3)填adtree(p->left,w);如果要插入的字符串大于此结点上字符串的值,则再次调用函数为空(4),即adtree(p->right,w)。在主函数中调用空(5),即adtree(root,word)。