gpt4 book ai didi

c - C 中的二叉搜索树并为重复键构建链表

转载 作者:行者123 更新时间:2023-11-30 21:08:20 25 4
gpt4 key购买 nike

typedef struct Node{
char Name[100];
char Value[2000];
struct Node *Same;
struct Node *left;
struct Node *right;
}yelp;

//more codes

//this is what I used to search the key within the BST
void search(yelp *root, char* key, char* OP_filename) {
yelp *current;
current = root;
int steps = 0, count= 0;
FILE *outputFile;
outputFile= fopen(OP_filename,"a");
while (current != NULL) {
if (strcmp(current->Name,key)==0) {
count++;
current = current->Same;
fprintf(outputFile,"%s --> %s\n", current->Name, current->Value );

}
if (strcmp(key,current->Name)<0){
current = current->left;
}
if(strcmp(key,current->Name)>0){
current = current->right;
}
steps++;
}
if(count ==0){
fprintf(outputFile,"%s --> NOTFOUND\n",key);
fprintf(stdout, "%s --> NOTFOUND \n",key);
}
else{
fprintf(stdout,"%s --> %d \n",key,steps);`enter code here`

}
fclose(outputFile);
}

我写了这个搜索方法,但它总是崩溃,而且我无法找到逻辑问题。它应该为具有相同键的项目构建一个 bst 和一个链接列表。请帮助我找到问题。由于我的英语水平不好,我可能无法清楚地解释我的问题,请问我这个问题。

最佳答案

假设树本身的实际实现是完美的!

实现评论者的提示并添加一些必要的检查会给出:

void search(yelp * root, char *key, char *OP_filename)
{
yelp *current;
int steps = 0, count = 0;
FILE *outputFile;

// might fail (most likely reason "too many open files")
outputFile = fopen(OP_filename, "a");
if (outputFile == NULL) {
fprintf(stderr, "Failure to open file\n");
return;
}

// early out (not abs. necessary, of course)
if (root == NULL) {
fprintf(stderr, "root is NULL\n");
fprintf(outputFile, "%s --> NOTFOUND\n", key);
fclose(outputFile);
return;
}

current = root;

while (current != NULL) {
if (strcmp(current->Name, key) == 0) {
count++;
// exchanged lines; see BLUEPIXY's comment for the reason
fprintf(outputFile, "%s --> %s\n", current->Name, current->Value);
current = current->Same;
} else if (strcmp(key, current->Name) < 0) {
current = current->left;
} else if (strcmp(key, current->Name) > 0) {
current = current->right;
}
steps++;
}
if (count == 0) {
fprintf(outputFile, "%s --> NOTFOUND\n", key);
fprintf(stdout, "%s --> NOTFOUND \n", key);
} else {
fprintf(stdout, "%s --> %d \n", key, steps);
}
fclose(outputFile);
}

关于c - C 中的二叉搜索树并为重复键构建链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39415901/

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