二进制搜索树的插入函数的void实现错误(C语言)

问题描述 投票:-1回答:1

在一次作业中,我被要求写一个二进制搜索树的插入函数,其中项指向一个结构,该结构中存放着一个词,以及它出现的次数。在搜索了二进制搜索树的插入函数的标准实现后,我想到了这个。

// Insert an item into the tree rooted at node n.
// If the tree already has a node for that item, do nothing.

void insert(BSTnode *n, void *item, int compare(void * a, void * b)){
  BSTnode *new_node = (BSTnode *)item;
  BSTnode *currentNode = n;
    if(n==NULL){
      BSTnode *new = createNode(item);
      return new;
    }

    else if(compare(((WordCount*)new_node->item)->word, ((WordCount*)currentNode->item)->word)==0){
      return;
    }

    else if(compare(((WordCount*)new_node->item)->word, ((WordCount*)currentNode->item)->word) > 0){
      n->right = insert(n->right, item, compare);
    }

    else{
      n->left = insert(n->left, item, compare);
    }
}

但是我得到了一个 "void value not ignored as it ought to be "的结果,因为我不能做... ...

 n->right = insert(n->right, item, compare);

如何修改这个插入函数?我被卡住了,真的不知道该怎么做,因为这是一个void函数。

c data-structures binary-search-tree void-pointers
1个回答
0
投票

试试这个

//start of insert
void insert(BSTnode *n, void *item, int compare(void * a, void * b))
{
    BSTnode *new_node = (BSTnode *)item;
    BSTnode *currentNode = n;
    if(n==NULL) // if root is null
    {
        BSTnode *node = createNode(item);
        n = node;
        return;
    }
    else
    {
        insertSub(n, item, compare); // walk over the tree recursive with itemsub
    }
}

void insertSub(BSTnode *n, void *item, int compare(void * a, void * b))
{
    BSTnode *new_node = (BSTnode *)item;
    BSTnode *currentNode = n;
    if(compare(((WordCount*)new_node->item)->word, ((WordCount*)currentNode->item)->word) > 0)
    {
        if(n->right == NULL) //if right child = null then create the desired node
        {
            n->right = createNode(item);
            return; // go out of the tree
        }
        else
        {
            insertSub(n->right, item, compare); walk
        }
    }
    else
    {
        if(n->left == NULL) //if left child = null then create desired node
        {
            n->left = createNode(item);
            return; // go out of the tree
        }
        else
        {
            insertSub(n->left, item, compare);
        }
    }
}

希望对你有所帮助:)

© www.soinside.com 2019 - 2024. All rights reserved.