为什么这个搜索功能返回一个指针的指针? [英] Why does this search function return a pointer to a pointer?

查看:108
本文介绍了为什么这个搜索功能返回一个指针的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 的#ifndef _BST_H_/ *返回负(左,下右),零(左==右),或正(左>右)。 * /
的typedef INT比较(void *的左边,无效*右);结构bst_node {
    void *的数据;
    结构bst_node *离开;
    结构bst_node *权利;
};结构bst_node * new_node(无效*数据);
无效free_node(结构bst_node *节点);
结构bst_node **搜索(结构bst_node **根,比较比较,无效*数据);
无效插入(结构bst_node **根,比较比较,无效*数据);
无效删除(结构bst_node **节点);#万一

这是一个头文件。
我不理解搜索的功能,为什么返回类型节点**

编辑:
添加的搜索FUNC这里:

 结构bst_node **搜索(结构bst_node **根,比较比较,无效*数据){
    结构bst_node **节点=根;
    而(*节点!= NULL){
        INT compare_result =对比(数据,(*节点) - GT;数据);
        如果(compare_result℃,)
            节点=及(*节点) - >左侧;
        否则如果(compare_result大于0)
            节点=及(*节点) - GT;的权利;
        其他
            打破;
    }
    返回节点;
}


解决方案

我猜想,该函数返回一个指针的指针,这样你的搜索可以用功能实施插入。如果搜索只返回一个指向一个节点,该节点没有找到,那么你必须重新走路的树要弄清楚什么指针,你需要重新连接做一个插入。如果它,而不是返回一个指向该结束了空的节点指针,那么插入可以通过只重新分配this指针指向需要插入新的节点来实现

只是一个猜测。

#ifndef _BST_H_

/* Returns negative (left<right), zero (left==right), or positive (left>right). */
typedef int comparator(void* left, void* right);

struct bst_node {
    void* data;
    struct bst_node* left;
    struct bst_node* right;
};

struct bst_node* new_node(void* data);
void free_node(struct bst_node* node);
struct bst_node** search(struct bst_node** root, comparator compare, void* data);
void insert(struct bst_node** root, comparator compare, void* data);
void delete(struct bst_node** node);

#endif

This is a header file. I don't understand about search function, why is the return type node**?

Edited: added search func here:

struct bst_node** search(struct bst_node** root, comparator compare, void* data) {
    struct bst_node** node = root;
    while (*node != NULL) {
        int compare_result = compare(data, (*node)->data);
        if (compare_result < 0)
            node = &(*node)->left;
        else if (compare_result > 0)
            node = &(*node)->right;
        else
            break;
    }
    return node;
}

解决方案

I would guess that the function returns a pointer to a pointer so that your search function can be used to implement insert. If search just returns a pointer to a node and the node isn't found, then you have to walk the tree again to figure out what pointer you need to rewire to do an insertion. If it instead returns a pointer to the node pointer that ended up being null, then insert can be implemented by just reassigning this pointer to point to the new node that needs to be inserted.

Just a guess.

这篇关于为什么这个搜索功能返回一个指针的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆