-
Notifications
You must be signed in to change notification settings - Fork 0
/
trie1.c
93 lines (87 loc) · 2.24 KB
/
trie1.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
#include<stdio.h>
#include<stdlib.h>
#define ALPHABET_SIZE 26
struct TrieNode{
struct TrieNode *children[ALPHABET_SIZE];
int isEndOfWord;
};
struct TrieNode* createNode(){
struct TrieNode *newNode = (struct TrieNode*)malloc(sizeof(struct TrieNode));
if(newNode){
for (int i = 0; i < ALPHABET_SIZE; i++) {
newNode->children[i] = NULL;
}
}
return newNode;
}
void insert(struct TrieNode *root, const char* word){
struct TrieNode *current = root;
while(*word){
int index = *word - 'a';
if(!current->children[index]){
current->children[index] = createNode();
}
current = current->children[index];
word++;
}
current->isEndOfWord = 1;
}
int search(struct TrieNode *root, const char* word){
struct TrieNode *current = root;
while(*word){
int index = *word - 'a';
if(!current->children[index]){
return 0;
}
current = current->children[index];
word++;
}
return current && current->isEndOfWord;
}
int main(){
struct TrieNode *root = createNode();
int op;
while(op!=3){
printf("1. Insert\n2.Search\n3.Exit\nEnter your Operation: ");
scanf("%d",&op);
if(op==1){
char word[100];
printf("Enter the word to be the inserted: ");
scanf("%s",word);
insert(root,word);
continue;
}
else if(op==2){
char word_search[100];
printf("Enter the word to be the searched: ");
scanf("%s",word_search);
printf("Search for %s: %s\n",word_search,search(root,word_search)?"Found":"Not Found");
continue;
}
else if(op==3){
printf("Thankyou!!");
break;
}
}
}
// 1. Insert
// 2.Search
// 3.Exit
// Enter your Operation: 1
// Enter the word to be the inserted: apple
// 1. Insert
// 2.Search
// 3.Exit
// Enter your Operation: 1
// Enter the word to be the inserted: mango
// 1. Insert
// 2.Search
// 3.Exit
// Enter your Operation: 2
// Enter the word to be the searched: app
// Search for app: Not Found
// 1. Insert
// 2.Search
// 3.Exit
// Enter your Operation: 2
// Enter the word to be the searched: apple