Because you do not know the list of words that appear in advance, you cannot easily sort and use binary lookups, and you cannot perform a linear lookup on each word in the input separately, and the overhead is too large-->o (n^n).
So consider using a two-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> #incl
Ude <ctype.h> #define MAXWORD/* 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 = ' + ';
return C;
} while (n > 0) {c = GetChar ();
if (Isalnum (c)) {*w++ = C;
} else {break;
} n--;
} *w = ' + ';
return w[0];
} int main () {tnode *root = null;//pointer must be initialized to 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
Reference: http://blog.csdn.net/roma823/article/details/6669925