[求助]生成一棵二叉树问题
大家帮我看看,程序那错了呢?编译通过了,可是,当我输入一个单词之后,回车,再输入单词,狂吃我内存呢?好郁闷呀!我用的VC++6.0//生成一棵二叉树,比较单词出现的次数
//c++ java Fortran basic Foxbase
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXWORD 20
struct tnode{
char *word; //指向一个单词
int count; //访问次数
struct tnode *left; //左孩子
struct tnode *right; //右孩子
};
char *GetWord() //读取单词
{
char *p;
if((p=(char*)malloc(MAXWORD+1))==NULL) {printf("Out of memory!\n");return(NULL);}
scanf("%MAXWORDs",p);
if(strlen(p)==0) return(NULL);
return p;
}
struct tnode *tree(struct tnode *p,char *w) //生成树
{
struct tnode *talloc();
int cond;
if(p==NULL)
{
p=talloc();
p->word=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=tree(p->left,w);
else
p->right=tree(p->right,w);
return(p);
}
void treeprint(struct tnode *point) //打印树
{
if(point!=NULL)
{
treeprint(point->left);
printf("%4d%s\n",point->count,point->word);
treeprint(point->right);
}
}
struct tnode *talloc()
{
return((struct tnode*)malloc(sizeof(struct tnode)));
}
int main()
{
struct tnode *root;
char *t=NULL;
root=NULL;
while((t=GetWord())!=NULL)
root=tree(root,t);
treeprint(root);
return 0;
}