K & amp; R_6.5 use a binary tree to count the number of times a word appears
Because you do not know the list of words that appear in advance, you cannot conveniently sort and use semi-query. You cannot perform a linear query for each word in the input, overhead --> O (n ^ n ).
Therefore, we consider using the binary tree data structure (O (n * logn) to organize these words as follows:
-----
/** My practice of K & R 6.5 **/# include
# Include
# Include
# Include
# 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; // the pointer must be initialized to 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
Reference: http://blog.csdn.net/roma823/article/details/6669925