K&R_6.5用二叉树统计单词出现的次数
2014-09-19 01:23
190 查看
因为预先不知道出现的单词列表,无法方便地排序并使用折半查找;也不能分别对输入中的每个单词都执行一次线性查找,开销太大-->O(n^n)。
所以考虑使用二叉树的数据结构(O(n*logn))来组织这些单词,实现如下:
-----
github:https://github.com/wusuopubupt/LearningC/blob/master/K%26R/chp6/binary_tree_word_counter.c
参考:http://blog.csdn.net/roma823/article/details/6669925
所以考虑使用二叉树的数据结构(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
相关文章推荐
- 统计所有'单词'出现的次数
- 搜索二叉树应用---判断单词正确与否,简单字典的实现,出现ip次数的统计
- 统计文章中单词出现的次数(续)
- 《C++ Primer》学习笔记:map容器insert操作的使用——编写程序统计并输出所读入的单词出现的次数
- 统计单词出现的次数并按单词出现的次数顺序输出单词及其次数
- 统计文本文件中单词出现次数最多的单词
- 统计单词出现的次数
- 使用map容器,统计输入的单词出现的次数
- 一道笔试题:统计文件中的单词出现次数
- 统计文件中某个单词出现的次数
- 二叉树统计单词的个数,若单词第一次出现,则产生新的树节点
- 利用Map实现的统计每个输入字符串或则单词出现的次数
- F# 统计一段英文文章中不同单词出现的次数
- 统计文件中某个单词出现的次数
- 统计文章中单词出现的次数
- 统计海量文章内容中出现次数前K大的单词并输出(完整实现)
- (转)F# 统计一段英文文章中不同单词出现的次数
- 统计一篇英文文件中,单词出现的次数,并按单词的长度进行排序
- List列表实现统计文档中单词出现的次数
- C# 实现统计字符串中不同单词的出现次数【百度笔试题】