带有 C 指针的二叉搜索树

  • 本文关键字:搜索树 指针 带有 c
  • 更新时间 :
  • 英文 :


我是C语言的新手。我的任务是实现二叉搜索树。所以,我真的很困惑指针。虽然,这个概念在琐碎的情况下很清楚,但在结构中使用指针对我来说是令人困惑的。

我有标题

#include <stdio.h>
typedef struct node_st {
int value;
struct node_st *leftchild;
struct node_st *rightchild;
} node;
typedef struct tree_st {
int size;
node root; 
} tree;  
extern void insert(tree *t, int value);

我想实现插入。这是我的尝试

extern void insert(tree *t, int value) {
int size = t->size;
node insertNode;
node *toInsert = &insertNode; 
toInsert->value = value;                  
toInsert->leftchild = NULL;
toInsert->rightchild = NULL;
if(size == 0) {
t->root = toInsert; 
t->size++; 
} else {
node *current; 
current = t->root;                  
for(int i = 0; i < size; ++i) {
if(current->value < value) {
if(current->rightchild != NULL) {
current = current->rightchild; 
}
else {
current->rightchild = toInsert;
t->size++; 
break;      
}
} else if(current->value > value) {
if(current->leftchild != NULL) {
current = current->leftchild; 
}
else {
current->leftchild = toInsert;
t->size++; 
break;      
}
} else {
printf("The value has been already inserted"); 
}
}

}
}

我收到以下错误:

/

usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/Scrt1.o: In 功能_start': (.text+0x20): undefined reference to主 collect2:错误:ld 返回 1 个退出状态

问题与问题:

  1. 该错误意味着什么?
  2. 函数中的所有指针是否正确?
  3. 是否有必要将 root 定义为struct node_st中的指针 都?

node insertNode;是在函数insert的作用域中声明的局部变量。
如果函数终止,则变量将丢失。

您必须通过以下malloc分配动态节点:

node *toInsert = malloc(sizeof(node ));

struct tree_st中,元素根不是指向节点的指针,而是节点本身。
这会导致赋值t->root = toInsert;不起作用,因为toInsert是指向节点的指针。

更改数据类型struct tree_st以使其正常工作。元素root也应该是指向节点的指针:

typedef struct tree_st {
int size;
node *root; 
} tree; 

最新更新