Trie字典树 动态内存

Trie字典树

 1 #include "stdio.h"
 2 #include "iostream"
 3 #include "malloc.h"
 4 #include "string.h"
 5 
 6 using namespace std;
 7 
 8 #define MAX_SIZE 26
 9 
10 typedef struct Trie{
11     char val;
12     bool isword;
13     struct Trie* child[MAX_SIZE];
14 }Node,*Trie_pointer;
15 
16 Trie_pointer CreateNode()
17 {
18     Trie_pointer node;
19     node = (Trie_pointer)malloc(sizeof(Node));
20     memset(node,0,sizeof(0));
21     return node;
22 }
23 
24 void Insert(Trie_pointer root, char *s)
25 {
26     Trie_pointer tmp,t = root;
27     char *p = s;
28     if(*s == '\0')
29         return;
30     while(*p != '\0')
31     {
32         if(t->child[*p - 'a'] == NULL)
33         {
34             tmp = CreateNode();
35             tmp->val = *p;
36             t->child[*p - 'a'] = tmp;
37         }
38         t = t->child[*p - 'a'];
39         p++;
40     }
41     t->isword = 1;
42 }
43 
44 bool Search(Node root, char *s)
45 {
46     Trie_pointer t = &root;
47     char *p = s;
48     if(*s == '\0')
49         return false;
50     while(*p != '\0')
51     {
52         if(t->child[*p - 'a'] == NULL)
53             return false;
54         t = t->child[*p - 'a'];
55         p++;
56     }
57     if(t->isword == 0)
58         return false;
59     return true;
60 }
61 
62 int main()
63 {
64     Node root;
65     char s[20];
66     int i,n;
67     memset(&root,0,sizeof(Node));
68     cin>>n;
69     for(i=1; i<=n; i++)
70     {
71         cin>>s;
72         Insert(&root,s);
73     }
74     while(cin>>s)
75     {
76         int flag = Search(root,s);
77         if(flag)
78             printf("YES\n");
79         else
80             printf("NO\n");
81     }
82     return 0;
83 }

 

posted on 2016-09-13 19:59  lazzzy  阅读(335)  评论(0编辑  收藏  举报

导航