Вот код, который должен работать. Он работает на macOS 10.15.2 Catalina, используя G CC 9.2.0 и XCode 11.3.1 с установленным компилятором fussy и несколькими опциями отладки памяти. Он не пытается освободить созданный им tr ie; он должен (это хорошее упражнение, чтобы иметь возможность освободить структуры, которые вы строите).
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
/* Node structure of trie */
struct node
{
struct node *next[27]; // 26 for a-z and last one(26th index) is for apostrophe
int end; // value as 1 denotes the end of the word.
};
/* This method is for creating a new node */
static struct node *createNode(void)
{
struct node *newNode = (struct node *)malloc(sizeof(struct node));
newNode->end = 0; // set end as false i.e. 0
for (int i = 0; i < 27; i++) // set all children as NULL
newNode->next[i] = NULL;
return newNode;
}
/* This method is for inserting a word in the trie */
static void insert(struct node *root, char *word)
{
struct node *curr = root;
int length = strlen(word);
for (int i = 0; i < length; i++) // iterating character by character
{
int index;
if (word[i] == '\'') // if character is apostrophe index is 26
index = 26;
else
index = tolower(word[i]) - 'a'; // else the index as the alphabet sequence number starting from 0.
// for a - 0, b - 1, ..... z - 25
if (!curr->next[index])
curr->next[index] = createNode(); // create node of that character if not created yet
curr = curr->next[index]; // then go for next character
}
curr->end = 1; // mark end as 1 to denote the ending of the word
}
/* This method is for searching a word in the trie */
static int search(struct node *root, char *word)
{
struct node *curr = root;
int length = strlen(word);
for (int i = 0; i < length; i++) // iterating character by character
{
/* Getting index same as insert function */
int index;
if (word[i] == '\'')
index = 26;
else
index = tolower(word[i]) - 'a';
if (!curr->next[index]) // if node of current character not found means the word doesn't exist in trie.
return 0;
curr = curr->next[index];
}
if (curr != NULL && curr->end) // if iterated all the characters and end is 1 then the word exists.
return 1;
else
return 0; // otherwise doesn't exist.
}
int main(void)
{
/* Reading the file line by line */
FILE *file;
size_t len = 1000;
char *word = (char *)malloc(len);
const char filename[] = "word.txt";
file = fopen(filename, "r");
if (file == 0)
{
fprintf(stderr, "Failed to open file '%s' for reading\n", filename);
exit(EXIT_FAILURE);
}
struct node *root = createNode();
while (fgets(word, len, file) != NULL) // iterating line by line
{
//int len = strlen(word);
//if (word[len - 1] == '\n') // removing the newline which is at the end of the every line
// word[len - 1] = '\0';
word[strcspn(word, "\r\n")] = '\0';
printf("Word: [%s]\n", word);
insert(root, word); // inserting every word
}
int ans;
word = (char *)("error's"); // checking the existence of the word "error's"
ans = search(root, word);
if (ans == 1)
printf("\"%s\" found!\n", word);
else
printf("\"%s\" not found!\n", word);
word = (char *)("hilli");// checking the existence of the word "hilli"
ans = search(root, word);
if (ans == 1)
printf("\"%s\" found!\n", word);
else
printf("\"%s\" not found!\n", word);
return 0;
}
Код работает правильно, если файл данных содержит подходящее подмножество этих строк:
enough
abracadabra
acid
test
hilli
error's
tests
testing
tested
tester
testosterone
acidly
acidic
Он был протестирован как с окончаниями строк DOS (CRLF), так и с Unix (NL или LF) и был безопасен с обоими, потому что он использует strcspn()
для удаления любого вида окончания строки:
word[strcspn(word, "\r\n")] = '\0';
Если бы у вас были старые окончания линий в стиле Ma c (только CR), то у вас возникли бы проблемы с fgets()
, не распознающими концы линий - но если вы это исправили (используя POSIX getdelim()
например), с такими строками он тоже будет работать корректно.
Изменения, внесенные в ваш код, в основном космеци c, но позволяют скомпилировать код чисто (источник trie79.c
; программа trie79
) используя довольно строгие параметры:
$ gcc -O3 -g -std=c11 -Wall -Wextra -Werror -Wmissing-prototypes -Wstrict-prototypes \
> trie79.c -o trie79
$