[英]Binary Tree storing any data type in c
我目前正在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;
}
您應該使用void指針插入值,然后再將其轉換為它們的假定類型。
問題是,如果您知道以后要比較哪個更大或更小,您就不會“獲得任何東西”。 我想您可能希望在您的節點中有一個附加信息,該信息指定實際值的類型。
我想您想進行練習,但是實際上您是否真的想將字符數組與整數進行比較?
#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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.