我一直在尝试在 C 中实现将字符插入到 trie 数据结构中的基本功能。我一直在试图找出我做错了什么,但在最后一天左右我被难住了/卡住了。
这是我写的一些代码:
TR head = NULL;
void initDict () {
head = NULL;
}
TR newNode (char item) {
TR temp;
temp = malloc (sizeof(*temp));
temp->thisChar = item;
temp->child = NULL;
temp->sibling = NULL;
return temp;
}
TR insertInOrder (char item, TR trie) {
if (trie == NULL) {
trie = newNode(item);
} else if (trie->thisChar < item) {
insertInOrder(item, trie->sibling);
} else if (trie->thisChar > item) {
char temp = trie->thisChar;
trie->thisChar = item;
insertInOrder(temp, trie->sibling);
}
return trie;
}
void insert (char *word) {
char letter = *word;
TR temp = NULL;
while (*word != '\0') {
letter = *word;
if (head == NULL) {
head = newNode(letter);
temp = head->child;
word++;
} else {
temp = insertInOrder(letter, temp);
temp->child = head->child;
head->child = temp;
word++;
}
}
}
我想不通这个...
PS checkLetter,是一个布尔函数,检查字母是否已经在trie里面(通过遍历trie结构,即trie = trie->sibling)
任何帮助将不胜感激=]
干杯!
编辑:更改了我的代码,以便 insertInOrder 返回一个值,但由于 insert 是一个 void 函数并且必须保持一个 void 函数,我不知道有一种方法可以将节点进一步插入到 trie 的头部(即 head ->孩子,头->孩子->孩子等)