-
Notifications
You must be signed in to change notification settings - Fork 12
/
trie.c
112 lines (107 loc) · 2.55 KB
/
trie.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include<stdio.h>
#include<stdlib.h>
struct trie
{
struct trie *alpha[26];
int wordflag;
};
typedef struct trie trie;
trie * root;
trie * createnode()
{
trie * node=(trie*) malloc(sizeof(trie));
int i=0;
for(;i<26;i++)
node->alpha[i]=NULL;
node->wordflag=0;
return node;
}
int search_insert_delete(trie *node, char *word, char mode)
{
if(!node)
{
if(mode=='i')
{
printf("\nCreating root node...");
node=createnode();
root=node;
}
else if(mode=='s' || mode=='d')
{
printf("\nRoot node does not exist.");
return 1;
}
}
while(*word)
{
int index=(*word|('A'^'a'))-'a';
if(!node->alpha[index])
{
if(mode=='i')
{
printf("\nCreating node for character '%c'...",*word);
node->alpha[index]=createnode();
}
else if(mode=='s' || mode=='d')
{
printf("\nNo node found for character '%c'.",*word);
return 1;
}
}
node=node->alpha[index];
word++;
}
if(!node->wordflag)
{
if(mode=='i')
{
printf("\nSetting wordflag...");
node->wordflag=1;
return 0;
}
else if(mode=='s' || mode=='d')
{
printf("\nWordflag not set."); return 1; }
}
else if(mode=='d')
{
printf("\nResetting wordflag...");
node->wordflag=0;
return 0;
}
else return 0;
}
main()
{
int ch;
do
{
char word[10];
int result;
printf("\n\n1. Enter into trie \n2. Search from trie \n3. Delete from trie \n4. Exit \n\nEnter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("\nEnter the word to be inserted: ");
scanf("%s",word);
result=search_insert_delete(root,word,'i');
if(!result) { printf("\nInsertion successful!"); }
break;
case 2: printf("\nEnter the word to be searched: ");
scanf("%s",word);
result=search_insert_delete(root,word,'s');
if(result==0) printf("\nSearch successful!\nThe word is present in the trie.");
else printf("\nSearch unsuccessful!\nThe word is not present in the trie!");
break;
case 3 : printf("\nEnter the word to be deleted: ");
scanf("%s",word);
result=search_insert_delete(root,word,'d');
if(result==0) printf("\nDeletion successful!");
else printf("\nSearch unsuccessful!\nThe word is not present in the trie!");
break;
case 4 : break;
default: break;
}
}
while(ch!=4);
}