我是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 个退出状态
问题与问题:
- 该错误意味着什么?
- 函数中的所有指针是否正确?
- 是否有必要将 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;