[英]binary search tree and struct errors
該程序應創建一個二進制搜索樹,在樹中插入數字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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.