gpt4 book ai didi

c - 前缀树中的插入和搜索实现

转载 作者:行者123 更新时间:2023-11-30 16:50:14 27 4
gpt4 key购买 nike

我正在开发一个带有前缀的实现,我试图构建以下内容

F->R->E->T->(纬度 + 经度)

我已经实现了插入功能,它似乎可以工作。我通过打印相应的纬度和经度值来验证这一点。

我遇到的问题是在我的搜索函数中,纬度和经度值返回(null)。此外,搜索功能确实会为某个单词返回 true。

目前我无法理解根本问题所在

插入函数

int trieInsert(struct trieNode *node, char *key, char *longitude, char *latitude){
struct trieNode *parent = node;
//printf("Longi: %s", longitude);
//printf(" ");
//printf("Latitude: %s \n", latitude);
if(key){
int index = 0;
int i = 0;

if(node){
while(key[i] != '\0'){
int indexVal = convertLetterToIndex(key[i]);
if(!parent->children[indexVal]){
parent->children[indexVal] = initializeTrie();
parent->children[indexVal]->value = key[i];
}
parent = parent->children[indexVal];
i++;
}

int longitudeLen = strlen(longitude);
int latitudeLen = strlen(latitude);

node->longi = malloc(longitudeLen + 1);
strncpy(node->longi, longitude, longitudeLen + 1);
node->longi[longitudeLen] = '\0';
//printf("Longi: %s", node->longi);
node->lat = malloc(latitudeLen + 1);
strncpy(node->lat, latitude, latitudeLen + 1);
node->lat[latitudeLen] = '\0';
//printf("Lati: %s \n", node->lat);

}
}
}

我的搜索功能

bool getTrie(struct trieNode *root, char *key){
struct trieNode *pNode = root;
bool flag = true;
if(!key){
printf("Word is empty \n");
return false;
}

if(!root){
printf("Trie is empty \n");
return false;
}
int i = 0;
while(key[i] != '\0'){
int indexVal = convertLetterToIndex(key[i]);
if(!pNode->children[indexVal]){
printf("Character not found in trie \n");
flag = false;
break;
}

pNode = pNode->children[indexVal];
i++;
}

printf("Longitude: %s", pNode->longi);
printf(" ");
printf("Latitude: %s \n", pNode->lat);

return flag;
}

在我的插入函数中,纬度和经度值添加正确吗?

编辑

我的结构的定义

struct trieNode{
char *longi;
char *lat;
struct trieNode *children[27];
char value;
};

最佳答案

所以我发现了我遇到的问题

而不是

node->longi = malloc(longitudeLen + 1);
node->lat = malloc(latitudeLen + 1);

应该是

parent->longi = malloc(longitudeLen + 1);
parent->lat = malloc(latitudeLen + 1);

关于c - 前缀树中的插入和搜索实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42270089/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com