Alg_trie: Count Word Frequency

Source: Internet
Author: User
# Include <stdio. h>
# Include <stdlib. h>
# Include <string. h>

# Define tree_width 256

# Define wordlenmax 128

// Count Word Frequency

Struct trie_node_st {
Int count;
Struct trie_node_st * Next [tree_width];
};

Static struct trie_node_st root = {0, {null }};

Static char * spaces = "\ t \ n /.\"\'()";

Static int
Insert (const char * word)
{
Int I;
Struct trie_node_st * curr, * newnode;

If (word [0] = '\ 0 '){
Return 0;
}
Curr = & root;
For (I = 0; ++ I ){
If (curr-> next [word [I] = NULL ){
Newnode = (struct trie_node_st *) malloc (sizeof (struct trie_node_st ));
Memset (newnode, 0, sizeof (struct trie_node_st ));
Curr-> next [word [I] = newnode;
}
If (word [I] = '\ 0 '){
Break;
}
Curr = curr-> next [word [I];
}
Curr-> count ++;

Return 0;
}

Static void
Printword (const char * STR, int N)
{
Printf ("% s \ t % d \ n", STR, N );
}

Static int
Do_travel (struct trie_node_st * rootp)
{
Static char worddump [wordlenmax + 1];
Static int Pos = 0;
Int I;

If (rootp = NULL ){
Return 0;
}
If (rootp-> count ){
Worddump [POS] = '\ 0 ';
Printword (worddump, rootp-> count );
}
For (I = 0; I <tree_width; ++ I ){
Worddump [POS ++] = I;
Do_travel (rootp-> next [I]);
Pos --;
}
Return 0;
}

Int
Main (void)
{
Char linebuf [200];
Size_t bufsize = 0;
Int ret;

While (1 ){
If (! Fgets (linebuf, 200-1, stdin )){
Break;
}

// While (1)
{
Char * word = linebuf;
If (WORD = NULL ){
Break;
}
If (word [0] = '\ 0 '){
Continue;
}
Insert (Word );
}
}

/* Free (linebuf );*/

Do_travel (& root );

Exit (0 );
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.