【发布时间】:2017-12-04 23:43:12
【问题描述】:
给定以下结构:
struct TElem {
int val;
};
typedef int TKey;
struct Node {
TKey key;
struct TElem *elem;
struct Node *left;
struct Node *right;
};
struct bst {
struct Node *root;
};
还有bst_Search和bst_Insert这两个函数。
struct TElem* bst_Search(struct bst *T, TKey c, struct Node **posins)
{
struct Node *q = T->root;
posins = &(T->root); // (1)
while (q)
if (q->key == c)
return q->elem;
else if ( c < q->key) {
q = q->left;
posins = &(q->left);
} else {
q = q->right;
posins = &(q->right);
}
return NULL;
}
void bst_Insert(struct bst *T, TKey c, struct TElem *x)
{
struct Node **posins;
struct TElem *v;
posins = malloc(sizeof *posins);
v = bst_Search(T, c, posins); // (2)
if (!v) {
struct Node *q = malloc(sizeof *q);
q->key = c;
q->elem = x;
q->left = NULL;
q->right = NULL;
*posins = q; // (3)
} else {
printf("Key exists %d\n", c);
}
free(posins);
}
而main() 是“主要”
struct bst *T = malloc(sizeof *T);
T->root = NULL;
struct TElem *x = elem_New(10);
bst_Insert(T, c, x);
我正在尝试插入一个新元素(elem_New 工作正常)到 BST,使用辅助函数 bst_Search 返回指向正确位置的指针 插入。 (1) 在首先将posins 指向T->root 内存地址时被调用。 (据我调试,这一切正常)。
然后posins 地址返回到调用函数bst_Insert,因为bst_Search 在(2) 找到了返回NULL 的位置。它在if 语句中正确设置q。然后在 (3),我希望 posins 指向的位置(在这种情况下 T->root 也指向的地址)现在应该重定向到新的树节点 @987654338 @。等效于T->root = q,但通过引用使用此调用。
【问题讨论】:
-
当您搜索树以找到存储节点的位置时,您无法真正返回 NULL 并在该位置进行分配。请记住,left 或 right 指针具有 NULL,因此您不能返回它并为其分配一些东西,否则您将遇到分段错误。一个简单的解决方案是返回父级并在其右指针上分配,或者复制搜索逻辑并添加到正确的位置。
-
@Isac
bst_Search返回NULL,但不在我正在使用的返回值(存储在v)中,我确实使用posins。 -
posins 将拥有来自
posins = &(q->right);的NULL。请记住,当q == NULL时退出,这意味着q->left和q->right在上一次迭代中是NULL。 -
posins实际上毫无意义。 -
BLUEPIXY @Isac ,是的。有道理..正在努力。
标签: c pointers binary-search-tree pass-by-reference