#include<stdio.h>
#include<ctype.h>
#include<string.h>
#include<stdlib.h>
#define MAXWORD 1000
struct tnode{
char *word ;
int count ;
struct tnode *left ;
struct tnode *right ;
};
int getword(char *,int) ; // 获取单词
struct tnode *
addnode(struct tnode *,char *) ; //将单词加入二叉排序树中
void treeprint(struct tnode *) ;
int main(int argc,char **argv)
{
struct tnode *root = NULL ;
char word[MAXWORD] ;
while((getword(word,MAXWORD) != EOF))
if(isalpha(word[0]))
root = addnode(root,word) ;
treeprint(root) ;
return 0 ;
}
/* 为节点和指针指向的单词分配空间 */
struct tnode *tmalloc(void) ;
char *strdup1(char *) ;
struct tnode *addnode(struct tnode *root,char *word)
{
int cond ;
if(root == NULL){ // 为空节点
root = tmalloc() ;
root -> word = strdup1(word) ; //这一个地方要注意,结构体成员word为指针,需要为它所指向的内容分配空间
root -> left = root -> right = NULL ;
root -> count = 1 ;
}
else if((cond = strcmp(word,root -> word)) == 0)
root -> count++ ;
else if(cond < 0)
root -> left = addnode(root -> left,word) ;
else
root -> right = addnode(root -> right,word) ;
return root ;
}
struct tnode *tmalloc(void)
{
return (struct tnode*) malloc(sizeof(struct tnode)) ;
}
char *strdup1(char *w)
{
char *p = (char *) malloc(strlen(w) + 1) ; // +1 for '\0'
if(p != NULL)
strcpy(p,w) ;
return p ;
}
void treeprint(struct tnode *root)
{
if(root != NULL){
treeprint(root -> left) ;
printf("%s %d\n",root -> word,root -> count) ;
treeprint(root -> right) ;
}
}
int getch(void) ;
void ungetch(int) ; //将输出压回到输入
int getword(char *w,int limit)
{
char c ;
char *word = w ;
while(isspace(c = getch()))
;
if(!isalpha(c)){
*word = '\0' ;
return c ;
}
*word++ = c ;
while(--limit > 0 && isalnum( c = getch() ) )
*word++ = c ;
if(c != EOF)
ungetch(c) ;
*word = '\0' ;
return *w ;
}
#define BUFFSIZE 1000
static int BUFF[BUFFSIZE] ;
static int buffp = -1 ;
int getch(void)
{
return (buffp > 0) ? BUFF[buffp--] : getchar() ;
}
void ungetch(int n)
{
if(buffp < BUFFSIZE)
BUFF[++buffp] = n ;
}
C语言二叉排序树单词计数程序实现
最新推荐文章于 2020-06-18 16:51:40 发布