C 实现二叉搜索树

发布于 2024-12-11 07:26:11 字数 175 浏览 0 评论 0原文

我一直在尝试用 C 语言实现 bst。我想我已经差不多完成了,但是在我的添加节点函数中,我创建了一个名为 current 的临时节点来存储树中访问的当前节点。然后,当我修改当前节点时,函数完成后我的原始指针不会被修改。

我已经阅读过有关此内容的内容,并且我认为我可能需要一个指针的指针,但我仍然不太知道如何更新原始结构。

I've been trying to implement a bst, in C. I think I'm almost there, but in my add node function, I create a temporary node called current to store the current node which is visited in the tree. Then when I modify the current node, my orignal pointer is not modified after the function finishes.

I've read up about this, and I think I may need a pointer of a pointer, but I stil don't quite know how to updated original struct.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

香橙ぽ 2024-12-18 07:26:11

你是对的,问题与指向 bstlist_add 中的指针有关。这是一个示例,可以帮助您弄清楚需要在代码中更改哪些内容。

int a=10;
int b=20;

void noChange(int * pSomeInt);
void change(int ** ppSomeInt);

int main(int argc,char * argv[])
{
    int * pMainInt=&a;

    noChange(pMainInt);
    //pMainInt will still point to a

    //since the parameter to change is int **, we have to use & here
    change(&pMainInt);
    //pMainInt now points to b

    return 0;
}

void noChange(int * pSomeInt)
{
    //while pSomeInt is a pointer, it is a copy of pMainInt, not a pointer to it 
    //so this creates a pointer to the parameter, pSomeInt, itself
    int ** ppSomeInt=&pSomeInt;

    //so this changes the parameter, pSomeInt
    *ppSomeInt=&b;
}

void change(int ** ppSomeInt)
{
    //ppSomeInt is a pointer to pMainInt, which is itself an int *
    //so *ppSomeInt is pMainInt and not a copy of it
    *ppSomeInt=&b;
}

You are right that the problem has to do with the pointer to a pointer in bstlist_add. Here's an example that should help you figure out what you need to change in your code.

int a=10;
int b=20;

void noChange(int * pSomeInt);
void change(int ** ppSomeInt);

int main(int argc,char * argv[])
{
    int * pMainInt=&a;

    noChange(pMainInt);
    //pMainInt will still point to a

    //since the parameter to change is int **, we have to use & here
    change(&pMainInt);
    //pMainInt now points to b

    return 0;
}

void noChange(int * pSomeInt)
{
    //while pSomeInt is a pointer, it is a copy of pMainInt, not a pointer to it 
    //so this creates a pointer to the parameter, pSomeInt, itself
    int ** ppSomeInt=&pSomeInt;

    //so this changes the parameter, pSomeInt
    *ppSomeInt=&b;
}

void change(int ** ppSomeInt)
{
    //ppSomeInt is a pointer to pMainInt, which is itself an int *
    //so *ppSomeInt is pMainInt and not a copy of it
    *ppSomeInt=&b;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文