1.这个算法是要实现一个trie tree, 但是我好像遇到了内存分配的问题,主要我是想要c语言实现. 报错信息的话,可以直接跑我那面那段代码,看看有什么问题。
#include
#include
#include
struct TrieNode {
struct TrieNode *children[MAX_SIZE];
bool isWord;
};
struct TrieNode* newTrieNode() {
struct TrieNode *node = (struct TrieNode *)malloc(sizeof(struct TrieNode *));
if (node == NULL)
exit(1);
int i;
memset(node->children, 0x0, sizeof(struct TrieNode *)*26);
node->isWord = false;
return node;
}
void insert(struct TrieNode root, char word) {
int i, length, index;
length = strlen(word);
if (length <= 0) return;
struct TrieNode *current = root;
for (i = 0; i < length; i++) {
index = word[i] - 'a';
if (current->children[index] == NULL) {
current->children[index] = newTrieNode();
}
current = current->children[index];
}
current->isWord = true;
}
bool search(struct TrieNode root, char word) {
int i, length, index;
length = strlen(word);
if (length <= 0) return true;
struct TrieNode *current = root;
for (i = 0; i < length; i++) {
index = word[i] - 'a';
current = current->children[index];
if (current == NULL) return false;
}
return current->isWord;
}
int main() {
struct TrieNode *root = newTrieNode();
insert(root, "hello");
printf("%d\n", search(root, "hello"));
free(root);
return 0;
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
//void insert(struct TrieNode root, char word)// -- 参数都应该是指针
void insert(struct TrieNode* root, char* word)
{
int i, length, index;
length = strlen(word);
if (length <= 0)
return;
struct TrieNode* current = root;
for (i = 0; i < length; i++) {
index = word[i] - 'a';
if (current->children[index] == NULL) {
current->children[index] = newTrieNode();
}
current = current->children[index];
}
current->isWord = true;
}
//bool search(struct TrieNode root, char word)// -- 参数是指针
bool search(struct TrieNode* root, char* word)
{
int i, length, index;
length = strlen(word);
if (length <= 0)
return true;
struct TrieNode* current = root;
for (i = 0; i < length; i++) {
index = word[i] - 'a';
current = current->children[index];
if (current == NULL)
return false;
}
return current->isWord;
}
其它没什么问题 ~
int main()
{
struct TrieNode* root = newTrieNode();
insert(root, "hello");
printf("%d\n", search(root, "hello"));
free(root);
return 0;
}