【发布时间】:2016-04-12 00:20:42
【问题描述】:
我正在制作一个预测文本界面,通过它我将字典存储到数据结构中(我使用了 trie),用户部分搜索一个单词,完成的单词显示为每个单词对应的数字。我已经完成了插入、搜索功能并进行了递归遍历,可以打印出所有完整的单词(没有数字)。但是我想将它们存储到一个结构中,以便我可以在另一个函数中使用它们,然后用户将看到带有相应数字的单词。
这是 main.c 代码(为了测试它不会进入输入所有 25 000 个单词的 readfile!):
struct TrieNode* root = trieRootConstructor();
struct TrieNode* pntr = NULL;
trieInsert(root, "aback");
trieInsert(root, "abacus");
trieInsert(root, "abalone");
trieInsert(root, "abandon");
trieInsert(root, "abase");
trieInsert(root, "abash");
trieInsert(root, "abate");
trieInsert(root, "abater");
int x = 0;
char* result = "";
char* search = "aba";
result = trieSearch(root, &pntr, search, result, &x);
printf("\n\n");
traverseTwo(pntr, search);
pntr 设置为部分单词结束的节点,这是遍历将搜索单词其余部分的位置。
这是我的递归遍历及其调用者:
void traverseTwo(struct TrieNode* node, char* partialWord)
{
char arr[50];
int index = 0;
int maxWordSize = 100;
char wordArr[50][maxWordSize];
index = recursivePrint(node->children, arr, wordArr[50], 0, partialWord, index);
int i = 0;
for(i = 0; i < index; i++)
printf("%d: %s\n", i, wordArr[i]);
printf("%d: Continue Typing", index);
}
int recursivePrint(struct TrieNode* node, char* arr, char* wordArr, int level, char* partialWord, int index)
{
if(node != NULL)
{
arr[level] = node->symbol;
index = recursivePrint(node->children, arr, wordArr, level+1, partialWord, index);
if(node->symbol == '\0')
index = completeWordAndStore(partialWord, arr, wordArr, index);
index = recursivePrint(node->sibling, arr, wordArr, level, partialWord, index);
}
return index;
}
int completeWordAndStore(char* partialWord, char* restOfWord, char* wordArr, int index)
{
int length = strlen(partialWord) + strlen(restOfWord);
char completeWord[length];
strcpy(completeWord, partialWord);
strcat(completeWord, restOfWord);
strcpy(wordArr[index], completeWord);
index++;
return index;
}
strcpy(wordArr[index], completeWord); 出现分段错误
这个想法(在我的脑海中)是,一旦它进入节点符号为 '\0' 的 if 语句,它将在索引值处存储字符串。
partial word 是搜索到的部分词 ee.g "aba",我会用 arr 对其进行 strcat 并将其存储到 struct 中。
结果应该是:
0:后退 1:算盘 2:鲍鱼 3:放弃 4:基础 5:阿巴什 6:减弱 7:消减 8:继续输入
我稍后确实调用了析构函数,但这绝对是经过测试的。
谁能建议如何修改它以便我可以存储字符串?
如果我是正确的,我还假设它将是一个数组结构?
非常感谢
杰克
【问题讨论】:
-
它可以是任何东西,从链表到哈希表等等……取决于你的用例。既然您说您已经完成了插入部分,那么理想情况下,这就是您将单词插入容器数据结构的位置。
-
@SelçukCihan 我只能使用 1 个数据结构。我使用特里树,插入用于将符号放入节点的特里树中。在搜索了一个 paritaal 单词后,我需要存储遍历中的其余单词并在另一个函数中使用它来向用户显示它,以便他们可以选择他们选择的单词...
-
哦,我明白了,您想将以给定搜索键开头的完整单词存储在另一个地方。由于您将让用户选择,因此列表不应该很长,因此您可以使用固定大小的字符串数组(即 char * 数组)。要快速尝试,只需在递归打印中再添加两个参数:第一个是将存储字符串的数组本身,第二个参数是该数组的索引。第二个参数将被递归调用修改,因此使其成为一个指向 int 的指针,并在每次插入后递增其值。
-
@SelçukCihan 非常感谢,当然我只想在达到 '\0' 节点时增加第二个参数???当您说 char* 数组时,您的意思是 char* arr[]??抱歉,编程问题对我来说不是很自然,所以我有时很难理解
-
@SelçukCihan 我已经按照你说的做了,但我不能使用 int* 否则我会收到警告,并且我在
strcpy(wordArr[index], completeWord);行中不断出现段错误
标签: c string recursion struct trie