我对如何做到这一点很困惑。我想我的主要问题实际上是用命令行参数打开文件,但是从所述文件中实现了add_to_tree
函数。
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int num;
struct Node* left;
struct Node* right;
}node;
node* add_to_tree(node* head, int number);
void print_in_order(node* head);
void print_in_reverse(node* head);
void free_tree(node* head);
int main(int argc, char** argv)
{
node* head=NULL;
int number;
char* input;
if(argc>2 || argc<2){
printf("\nCorrect Usage: ./a.out <input file>\n");
}
node* tree=add_to_tree(head, number);
print_in_order(tree);
return 0;
}
node* add_to_tree(node* head, int number)
{
char* input=argv[1];
FILE *cfptr=fopen(input, "r");
if(cfptr==NULL) {
printf("\nFIle could not be opened\n");
return 0;
}
while(fscanf(cfptr, "%d", &number)!=EOF){
if(head==NULL){
head=malloc(sizeof(node));
head->num=number;
head->left=NULL;
head->right=NULL;
}
else if(number< head->num){
add_to_tree(head->left, number);
}
else if(number> head->num){
add_to_tree(head->right, number);
}
}
return head;
}
void print_in_order(node* head)
{
if(head==NULL){
return;
}
node* current=head;
while(current!=NULL){
printf("\n Temp=%d\n", current->num);
}
}
我也一直坚持如何打印树一般(结构中没有下一个指针,所以在printf
我不能current=current->next
之后。)