【发布时间】:2011-08-27 21:32:55
【问题描述】:
我一直在尝试在 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++;
}
}
}
我想不通...
P.S checkLetter,是一个布尔函数,检查字母是否已经在trie内(通过遍历trie结构,即trie = trie->sibling)
任何帮助将不胜感激 =]
干杯!
编辑:更改了我的代码,以便 insertInOrder 返回一个值,但由于 insert 是一个 void 函数并且必须保持为 void 函数,我不知道有一种方法可以将节点进一步插入到 trie 的头部(即 head->child、head->child->child 等)
【问题讨论】:
-
是的,它可以编译,除了客户端、头文件和它编译的缺少的 checkLetter 函数之外,但是在 insert() 函数中 temp = temp->child 行周围出现了段错误
-
删除了我的评论。刚刚注意到你的 TR typedef。虽然不喜欢。非常混乱