gpt4 book ai didi

c - 二叉搜索树和结构错误

转载 作者:行者123 更新时间:2023-11-30 17:07:29 25 4
gpt4 key购买 nike

该程序应创建一棵二叉搜索树,将数字 1-366 插入到树中,然后提示用户输入一个数字以查看该数字是否在二叉搜索树中。当所有内容都在一个 C 文件中时它可以工作,但我现在需要将其模块化并将 main 放在一个单独的文件中,但它现在给我带来了我不明白的错误。

我有 3 个文件:

map .h:

#include <stdbool.h>

typedef struct tree Tree;
typedef struct node Node;

//creates a new tree
Tree *new_tree();

//create a new node
Node* NewNode(int data);

//insert in to the binary tree
Node* insert(Node* node, int data);

//search for nodes to see if they exist
bool NodeSearch(Node* node,int data);

map .c:

//Binary search tree implementation
#include <stdio.h>
#include <stdlib.h>
#include "map.h"

//node structure
struct node {
int data;
struct node* left;
struct node* right;
} ;

//tree wrapper structure
struct tree {
struct node *root;
} ;

//create a new tree
Tree *new_tree() {
Tree *t = malloc(sizeof(Tree));
t->root = NULL;
return t;
}

//create a new node
Node* NewNode(int data) {
Node* node = malloc(sizeof *node); // "new" is like "malloc"
node->data = data;
node->left = NULL;
node->right = NULL;

return(node);
}

//insert in to the binary tree
Node* insert(Node* node, int data) {
// 1. If the tree is empty, return a new, single node
if (node == NULL) {
return(NewNode(data));
}
else {
// 2. Otherwise, recur down the tree
if (data <= node->data) node->left = insert(node->left, data);
else node->right = insert(node->right, data);

return(node); // return the (unchanged) node pointer
}
}
//search for nodes to see if they exist
bool NodeSearch(Node* node,int data) {
if(node==NULL) return false;
else if(node->data == data) return true;
else if(data <= node ->data) return NodeSearch(node->left, data);
else return NodeSearch(node->right, data);
}

mainphone.c:

# include "map.h"
# include <stdio.h>
# include <stdlib.h>

int main(){
struct node* root = NULL;

for (int i = 1; i < 367; i++) {
root = insert(root,i);
Node *n = NewNode (i);
insert (n, n->data);}

int number;
printf("Enter Number\n");
scanf("%d",&number);
if(NodeSearch(root, number) == true) printf("Found\n");
else printf("Not found\n");


}

它给我的错误是:

mainphone.c:11:15: error: incomplete definition of type 'struct node'
insert (n, n->data);}
~^

./map.h:4:16: note: forward declaration of 'struct node'
typedef struct node Node;
^

mainphone.c:16:5: error: implicit declaration of function 'NodeSearch' is
invalid in C99 [-Werror,-Wimplicit-function-declaration]
if(NodeSearch(root, number) == true) printf("Found\n");

最佳答案

第一个错误是因为虽然main.c有结构体节点的声明,但实际的结构体定义在map.c中,而mainphone.c并不知道。

现在这通常是一件好事,因为它迫使我们封装。如果您想将结构保留在 map.c 中,则需要创建函数以从外部访问其数据。

第二个错误很可能是编译错误。确保将之前编译的map.o链接到mainphone.c:

gcc (FLAGS_HERE) map.c -c
gcc (FLAGS HERE) map.o mainphone.c -o (YOUR_EXECUTABLE_NAME)

或使用自动 *.c 语法。

gcc (FLAGS_HERE) *.c -o (YOUR_EXECUTABLE_NAME)

关于c - 二叉搜索树和结构错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34050539/

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