【发布时间】:2015-11-27 05:07:31
【问题描述】:
我正在尝试在C 中实现一个 trie 数据结构,但无法弄清楚如何动态命名添加到字典中的新节点。请参阅我的 add 方法的最后几行,我在其中尝试创建一个新节点并尝试指向它。
bool add(char *word, node tree)
{
// Creates a variable to store the current char in the string
char currChar = word[0];
// Converts the current char to an index #
int currCharIndex = ((int) toupper(currChar)) - 65;
// Checks if we've reached the end of the word
if (currChar == '\0')
{
// Sets current node word to true
tree.word = true;
}
// Checks if next letter in word is not NULL
else if (tree.children[currCharIndex] != NULL)
{
// Follows the pointer
return add(&word[1], *tree.children[currCharIndex],);
}
else
{
//Creates a new node
node; // TODO: name node
// Points the current node to the new node
tree.children[currCharIndex] = &// TODO: new node name
return add(&word[1], *tree.children[currCharIndex]);
}
}
这是我对node的定义:
typedef struct node
{
bool word;
struct node *children[26];
}
node;
bool search(char *word, node tree);
bool add(char *word, node tree);
int main(void)
{
node dictionary;
}
【问题讨论】:
-
请说明
node的定义方式,以便 SO 为您提供帮助。node传递给add(按值传递)的方式看起来不对。您可能需要将指针传递给node。同样,您不能将局部变量node <whatever-name>添加到add,因为它会超出范围。你需要使用malloc分配内存,然后添加。