我遇到了很多麻煩。我已經看了很多例子和類似的實現,我仍然無法弄清楚爲什麼這不起作用。出於某種原因,我的代碼正在獲取每個新值並使其成爲新的頭,並從本質上刪除上一棵樹。除了插入值,它說的頭是空每次和重寫存儲於頭價值...以下是我的代碼:嘗試在C中使用掃描值創建二進制搜索樹
typedef struct studentRec{
int id;
char name[25]; //the name has a maximum length of 25 letters
char major[15]; //the major array has a max length of 15
int year;
struct studentRec *left, *right;
}student;
student* createNode(int ID, char *name, char *major, int year);
student* initBST(FILE *input, char *argv);
student* addNode(student *head, int ID, char *name, char *major, int year);
int Search(student *head);
void printInorder(student *n);
int main(int argc, char *argv[]){
FILE *input;
printf("This is the name of input: %s\n", argv[1]);
student *mainHead = malloc(sizeof(student*));
mainHead = initBST(input, argv[1]);
printInorder(mainHead);
return 0;
}
student* initBST(FILE *input, char *argv){
int ID = -1;
input = fopen(argv, "r");
fscanf(input, "%d", &ID);
student *head = malloc(sizeof(student*));
int grade = -1;
while(ID != 0){
char *first, *last, *major, *name;
first = malloc(25*sizeof(char));
last = malloc(25*sizeof(char));
major = malloc(25*sizeof(char));
name = malloc(25*sizeof(char));
fscanf(input, "%d", &ID);
if(ID == 0){
break;
}
fscanf(input, "%s %s %s %d", first, last, major, &grade);
sprintf(name, "%s %s", first, last);
head = addNode(head, ID, name, major, grade);
}
return head;
}
void printInorder(student *n){
if(n != NULL){
printInorder(n->left);
printf("This is the current value of ID: %d\n", n->id);
printInorder(n->right);
}
}
student* createNode(int ID, char *name, char *major, int year){
printf("Adding this ID value: %d\n", ID);
student *new = malloc(sizeof(student*));
new->left = NULL;
new->right = NULL;
new->id = ID;
strcpy(new->name, name);
strcpy(new->major, major);
new->year = year;
return new;
}
student* addNode(student *head, int ID, char *name, char *major, int year){
if(head == NULL){
printf("head == NULL\n");
return createNode(ID, name, major, year);
}
else{
if(ID < head->id){
return head->left = addNode(head->left, ID, name, major, year);
}
else if(ID > head->id){
return head->right = addNode(head->right, ID, name, major, year);
}
}
}
這是很多代碼。你有沒有嘗試過使用調試器來完成它? – 2014-11-23 21:35:29
嗯,我剛剛在幾天前安裝了Linux Mint。我不確定什麼樣的調試器可用。我只是使用gedit。有調試器的插件嗎? – Scrungo 2014-11-23 21:37:26
outch :-) gedit可能不是編寫代碼的最佳工具。對於調試器,請嘗試'gdb'。大量的教程在那裏... – 2014-11-23 21:38:34