統計輸入中所有單詞出現的次數(使用二叉查找樹實現:遞歸和非遞歸)

/*@function:統計輸入中的所有單詞出現的次數
 * @method: 使用二叉查找樹。對輸入的單詞建立一顆二叉查找樹,新輸入的單詞若存在於樹中,則增加該節點的計數值;否則,新增一個節點
 */
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>

#define MAXWORD 	100

typedef struct tnode
{
	char 	word[MAXWORD];
	int 	count;
	struct tnode *left;
	struct tnode *right;
}tnode_t;

tnode_t *addtree(tnode_t *, char *);
void treeprint(tnode_t *);
int getword(char *, int);



main(void)
{
		tnode_t *root;
		char word[MAXWORD];
		
		root = NULL;
		while(getword(word, MAXWORD) != EOF)
			if(isalpha(word[0]))
				root = addtree(root, word);
		treeprint(root);
		return 0;
}

/* add a node to the tree by using non-recursive method */
/*
tnode_t *addtree(tnode_t *p, char *w)
{
	int cond;
	tnode_t *s, *temp1, *temp2;//s爲待插入的node,temp2爲temp1的父節點
	s = (tnode_t *)malloc(sizeof(tnode_t));
	if(s == NULL)
	{
		printf("error: malloc\n");
		exit(0);
	}
	strcpy(s->word, w);
	s->count = 1;
	s->left = s->right = NULL;
	if(p == NULL) //if tree is empty
	{
		p = s;
		return p;
	}
	temp1 = p;
	while(temp1 != NULL) //find the place to insert
	{
		temp2 = temp1;
		if((cond = strcmp(w, temp1->word)) < 0)
			temp1 = temp1->left;
		else if(cond == 0) //if the node is existed, count increases, and free memory of s
		{
			temp1->count++;
			free(s);
			return p;
		}
		else
			temp1 = temp1->right;
	}
	if((cond = strcmp(w, temp2->word)) < 0)
		temp2->left = s;
	else
		temp2->right = s;
	return p;
}
**/

/* add a node to the tree by using recursive method */
tnode_t *addtree(tnode_t *p, char *w)
{
	int cond;
	tnode_t *s;
	
	if(p == NULL) //基準
	{
	    s = (tnode_t *)malloc(sizeof(tnode_t));
		if(s == NULL)
		{
			printf("error: malloc\n");
			exit(0);
		}
		strcpy(s->word, w);
		s->count = 1;
		s->left = s->right = NULL;
		p = s;
		return p;
	}
	else if((cond = strcmp(w, p->word)) < 0)
		p->left = addtree(p->left, w);//note
	else if(cond == 0)
		p->count++;
	else 
		p->right = addtree(p->right, w);
	return p;
}

/***********************************/
/* inorder print */
void treeprint(tnode_t *p)
{
	if(p != NULL)
	{
		treeprint(p->left);
		printf("%s\t%d\n", p->word, p->count);
		treeprint(p->right);
	}
}

/***********************************/
int getword(char *word, int lim)
{
	int c;
	char *w = word;
	
	while(isspace(c = getchar())) //檢查參數c是否爲空格字符,即爲下一個字母的開始
		;
	if(c != EOF)
		*w++ = c;
	if(!isalpha(c)) //判斷字符變量c是否爲字母
	{
		*w = '\0';
		return c;
	}
	for(; --lim > 0; w++)
		if(!isalnum(*w = getchar())) //判斷字符變量c是否爲字母或數字
			break;

	*w = '\0';
	return word[0];
}


發佈了37 篇原創文章 · 獲贊 14 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章