我目前正在c中实现二叉树。在获取用于插入int的代码之后,我现在希望树能够存储任何日期类型,即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;
}
答案 0 :(得分:1)
您应该使用void指针插入值,然后将它们转换为假定的类型。
问题是,如果你知道你想要比较哪个更大或更小,你不会得到“任何东西”。我想您可能希望在节点中有一个额外的信息,它指定实际值的类型。
我想你想练习这个,但实际上你真的想要用正整数比较字符数组吗?
答案 1 :(得分:0)
#include <stdio.h>
#include <stdlib.h>
struct node {
void *value;
struct node *p_left;
struct node *p_right;
};
typedef int (*Compare)(const void *, const void *);
void insert(void* key, struct node** leaf, Compare cmp){
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( cmp(key, (*leaf)->value) < 0) {
printf( "\ngoing left " );
insert( key, &(*leaf)->p_left, cmp);
} else if( cmp(key, (*leaf)->value) > 0){
printf( "\ngoing right " );
insert( key, &(*leaf)->p_right, cmp);
} else {
free(key);
}
}
int CmpInt(const int *a, const int *b){
return *a < *b ? -1 : *a > *b;
}
int *GetInteger(void){
char line[16];
printf("Please enter a value : ");
if(fgets(line, sizeof line, stdin)){
int v, *ret;
char *p;
v = strtol(line, &p, 10);
if(*p == '\n' || *p == '\0'){
int *ret = malloc(sizeof(*ret));
*ret = v;
return ret;
}
}
return NULL;
}
void print_tree(struct node *root, void (*print_func)(const void*) ){
if(root){
print_tree(root->p_left, print_func);
print_func(root->value);
print_tree(root->p_right, print_func);
}
}
void print_int(const void *p){
printf("%d ", *(int*)p);
}
int main(void){
struct node *p_root = NULL;
void *value;//int *value;
while(value = GetInteger()){//upto input EOF or invalid input
insert(value, &p_root, (Compare)CmpInt);
}
print_tree(p_root, print_int);
//release tree omit
return 0;
}