K&R_6.5用二叉树统计单词出现的次数

因为预先不知道出现的单词列表,无法方便地排序并使用折半查找;也不能分别对输入中的每个单词都执行一次线性查找,开销太大-->O(n^n)。

所以考虑使用二叉树的数据结构(O(n*logn))来组织这些单词,实现如下:

-----

/*
 * My practice of K&R 6.5
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define MAXWORD 100

/* a binary tree node */
typedef struct tnode_ {
	char *word;
	int count;
	struct tnode_ *left;
	struct tnode_ *right;
} tnode;

void print_tree(tnode *root);
tnode *add_tree(tnode *root, char *word);
void free_node(tnode *root);

char *copy_string(char *s) {
	char *p = (char *)malloc(strlen(s)+1);
	if(p != NULL) {
		strcpy(p, s);
	}

	return p;
}

tnode *add_tree(tnode *p, char *word) {
	int result;
	if(p == NULL) {
		p = (tnode *)malloc(sizeof(tnode));
		p->word= copy_string(word); // Attention !
		p->count = 1;
		p->left = NULL;
		p->right = NULL;
	}
	else {
		result = strcmp(word, p->word);
		if(result < 0) {
			p->left = add_tree(p->left, word);
		}
		else if(result > 0) {
			p->right = add_tree(p->right, word);
		}
		else {
			p->count++;
		}
	}

	return p;
}

void print_tree(tnode *p) {
	if(p) {
		print_tree(p->left);
		printf("%s\t : %4d\n", p->word, p->count);
		print_tree(p->right);
	}
}

void free_node(tnode *p) {
	if(p) {
		free_node(p->left);
		free_node(p->right);
		free(p->word);
		free(p);
	}
}

int getword(char *word, int n) {
	int c;
	char *w = word;

	while(isspace(c = getchar())) {
		;
	}
	if(c != EOF) {
		*w++ = c;
	}
	if(!isalpha(c)) {
		*w = '\0';
		return c;
	}
	while(n > 0) {
		c = getchar();
		if(isalnum(c)) {
			*w++ = c;
		}
		else {
			break;
		}
		n--;
	}

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

int main() {
	tnode *root = NULL; // 指针一定要初始化为NULL
	char word[MAXWORD];

	while((getword(word, MAXWORD)) != EOF) {
		if(isalnum(word[0])) {
			root = add_tree(root, word);
		}
	}

	print_tree(root);

	free_node(root);

	return 0;
}

github: https://github.com/wusuopubupt/LearningC/blob/master/K%26R/chp6/binary_tree_word_counter.c

参考:http://blog.csdn.net/roma823/article/details/6669925

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值