在一次作业中,我被要求写一个二进制搜索树的插入函数,其中项指向一个结构,该结构中存放着一个词,以及它出现的次数。在搜索了二进制搜索树的插入函数的标准实现后,我想到了这个。
// 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函数。
试试这个
//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);
}
}
}
希望对你有所帮助:)