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 <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; // 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
K & r_6.5 use a binary tree to count the number of times a word appears