K&R_6.5用二叉樹統計單詞出現的次數

來源:互聯網
上載者:User

因為預先不知道出現的單字清單,無法方便地排序並使用折半尋找;也不能分別對輸入中的每個單詞都執行一次線性尋找,開銷太大-->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; // 指標一定要初始化為NULLchar 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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.