Due to the uncertainty of the words, binary trees are used for implementation:
[Cpp]
// TreeNode. h
Typedef struct _ TreeNode
{
Int count; // number of occurrences
Char * word; // Save the word
Struct _ TreeNode * left;
Struct _ TreeNode * right;
} TreeNode;
// Allocate memory to TreeNode
TreeNode * talloc (void)
{
Return (TreeNode *) malloc (sizeof (TreeNode ));
}
// Print the tree
Void tprint (TreeNode * root)
{
// Print left-> self-> right
If (root! = NULL)
{
Tprint (root-> left );
Printf ("% 4d % s \ n", root-> count, root-> word );
Tprint (root-> right );
}
}
// Add words to a proper Node
TreeNode * addNode (TreeNode * node, const char * word)
{
Int con;
TreeNode * tmp;
If (node = NULL)
{
Node = talloc ();
Node-> count = 1;
Node-> word = strdup (word );
Node-> left = node-> right = NULL;
} Else if (con = strcmp (word, node-> word) <0)
{
Tmp = addNode (node-> left, word );
Node-> left = tmp;
} Else if (con> 0)
{
Tmp = addNode (node-> right, word );
Node-> right = tmp;
} Else {
Node-> count ++;
}
Return node;
}
/**
Reads words from a specified stream.
*/
Int getWord (char * ch, size_t n, FILE * f)
{
Int c;
Char * p = ch;
While (isspace (c = fgetc (f )))
;
If (c! = EOF)
* P ++ = c;
If (! Isalpha (c ))
{
* P = '\ 0 ';
Return c;
}
For (; -- n> 0; p ++)
{
If (! Isalpha (* p = fgetc (f )))
{
Ungetc (* p, f );
Break;
}
}
* P = '\ 0 ';
Return c;
}
// Whether the tree Memory is used
Void treeFree (TreeNode * root)
{
If (root! = NULL)
{
TreeFree (root-> left );
Free (root-> word); // release the memory occupied by the word on the node
Free (root); // whether the node memory is occupied
TreeFree (root-> right );
}
}
// Test. c
# Include <stdio. h>
# Include <stdlib. h>
# Include "TreeNode. h"
# Deprecision MAX 100
Int main (int argc, char * argv [])
{
FILE * f;
Char w [MAX] = {0 };
Char * fname = "TreeNode. h ";
If (f = fopen (fname, "r "))! = NULL)
{
TreeNode * root = NULL;
While (getWord (w, MAX, f )! = EOF ))
{
If (isalpha (w [0])
Root = addNode (root, w );
}
Tprint (root );
TreeFree (root );
Fclose (f );
} Else {
Printf ("open % s error \ n", fname );
}
Getchar ();
Return 0;
}