【发布时间】:2014-11-07 20:53:35
【问题描述】:
我目前正在 c 中实现二叉树。在让代码工作以插入整数之后,我现在希望树能够存储任何日期类型,即 char 等。我对如何去做这件事有点难过。我听说/看到我可以在我的节点结构中使用 void*,但不确定如何在插入元素和比较 void* 以查看哪个更大或更小方面实现这一点。任何帮助将不胜感激!谢谢
#include <stdio.h>
#include <stdlib.h>
//struct for node of the binary tree
struct node
{
void *value;
struct node *p_left;
struct node *p_right;
};
//recursive function to allow users to input into the tree
void insert(void* key, struct node** leaf )
{
if( *leaf == NULL )
{
*leaf = (struct node*) malloc( sizeof( struct node ) );
(*leaf)->value = key;
(*leaf)->p_left = NULL;
(*leaf)->p_right = NULL;
printf( "\nnew node " );
}
else if( key < (*leaf)->value )
{
printf( "\ngoing left " );
insert( key, &(*leaf)->p_left );
}
else if(key > (*leaf)->value)
{
printf( "\ngoing right " );
insert( key, &(*leaf)->p_right );
}
}
int main(void)
{
struct node *p_root = NULL;
int value ; //i want value to be of any kind
printf( "\nPlease enter a value: " );
scanf( "%d", &value );
insert(value, &p_root);
return 0;
}
【问题讨论】:
-
比较是困难的部分,您必须想出一种方法来比较不同类型的元素,即如何比较字符串和浮点数?我认为在您开始编写该部分之前要尝试并弄清楚这一点。
-
通过创建比较函数传递给
insert函数(int cmpInt(const void*, const void*),int cmpStr(const void*, const void*))。 -
非常感谢@BLUEPIXY,您能否解释一下这条线的工作原理:
return *a < *b ? -1 : *a > *b;
标签: c pointers tree binary-tree void