二叉搜索树和结构错误

时间:2015-12-02 18:43:07

标签: c struct binary-search-tree

该程序应该创建一个二叉搜索树,将数字1-366插入树中,然后提示用户输入一个数字以查看该数字是否在二叉搜索树中。当它全部在一个C文件中时它起作用但我现在需要使它模块化并且在一个单独的文件中有主要但它现在给我错误,我不明白。

我有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");

1 个答案:

答案 0 :(得分:0)

第一个错误是因为当main.c具有struct节点的声明时,实际的结构定义在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)

或使用automagical * .c语法。

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