以前写过trie的, 但是这次再写, 发现了很多问题, 看来, 我对trie掌握得还不够啊……
#include<iostream>
#include<string>
#include<cstring>
#include<cstdio>
using namespace std;
struct Node
{
Node *next[26];
int num;
Node()//构造函数
{
num=1;
for(int i=0; i<26; i++)
next[i]=NULL;
}
};
void Insert(Node* &root, char* str)
{
Node *p=root;
if( p==NULL )
{
p=new Node();
root=p;//这个root是要带回主函数的
}
for(int i=0; str[i]!='\0'; i++)
{
if(p->next[str[i]-'a'] != NULL)
{
p->next[str[i]-'a']->num++;//当初写的时候写成了p->num++!
}
else
p->next[str[i]-'a']=new Node();
p=p->next[str[i]-'a'];
}
}
int Search(Node *root, char* str)
{
for(int i=0; str[i]!='\0'; i++)
{
if( root->next[str[i]-'a']==NULL ) return 0;
else root=root->next[str[i]-'a'];
}
return root->num;
}
int main()
{
char str[11];
Node *root=NULL;
while( gets(str) && str[0]!='\0')//对其输入的控制
{
Insert(root, str);
}
while( cin>>str )
{
cout<<Search(root, str)<<endl;
}
}