1
#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

これはヘッダーファイルです。関数について理解していませんがsearch、なぜ戻り型なのnode**ですか?

編集:ここに検索機能を追加:

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;
}
4

1 に答える 1

2

search関数を使用してを実装できるように、関数はポインターへのポインターを返すと思いますinsert。ノードへのポインタを返すだけでノードが見つからない場合searchは、ツリーをもう一度歩いて、挿入を行うために再配線する必要のあるポインタを特定する必要があります。代わりに、nullになったノードポインタへのポインタを返す場合は、insert挿入する必要のある新しいノードを指すようにこのポインタを再割り当てするだけで実装できます。

ただの推測。

于 2011-03-21T04:48:21.397 に答える