【发布时间】:2013-12-25 14:51:20
【问题描述】:
编译时似乎有错误,但不确定是什么。我已经经历了几次,不知道为什么。
另外,我还应该做些什么来改进这段代码?
#include <stdlib.h>
#include <stdio.h>
//create structure to hold node
typedef struct node
{
int data;
struct node *left; //lower no. / points to left node
struct node *right; //higher no. / points to right node
} node;
void insert(node **rt, int val) //insertion function
{
node *tmp;
if(*rt == NULL){
tmp = (node *) malloc(sizeof(node)); //allocates memory for node
if (tmp == NULL)
{
printf(stderr, "Unable to allocate node\n");
exit(1);
}
tmp->data = val;
*rt = tmp;
}
else{
if(val > (*rt)->data)
insert(&(*rt)->right, val);
else
insert(&(*rt)->left, val);
}
}
void print_node(node *head) //starts with head/first node until NULL
{
if(head == NULL)
return;
if(head->left != NULL)
print_node(head->left);
printf("data = %d\n", head->data);
if(head->right != NULL)
print_node(head->right);
}
int main(int argc, char *argv[])
{
int value[6] = {20,10,5,17,30,21}; //values put into array
int i; //i count
node *head = NULL;
for(i = 0; i < 6; i++) //loop array
{
insert(&head, value[i]);
}
print_node(head); //recursive search
return 0;
}
【问题讨论】:
-
编译时还是运行时?编译器崩溃会很奇怪。如果在运行时,您应该调试以缩小问题范围。
标签: c data-structures binary-tree nodes