我試圖用下面的結構創建學生的鏈表。學生結構的鏈表實現
struct student
{
int student_ID;
char *student_name;
struct course *courses_enrolled;
Student *child;
};
//Insert student to the list with a given student pointer and the starting point
Student *insert_student(Student *child, Student *root)
{
Student *temp = (Student*)malloc(sizeof(Student));
//if there isn't a starting point, declare this as the start point
if(root->student_name == NULL)
{
root->student_ID = child->student_ID;
root->student_name = strdup(child->student_name;);
root->child = NULL;
}
//if this student's name is before current node, replace node.
else if(strcmp(child->student_name, root->student_name) < 0)
{
temp = root;
root = child;
child->child = temp;
}
//if this student's name is after current node, keep doing insert recursion
else if(strcmp(child->student_name, root->student_name) > 0)
{
insert_student(child, root->child);
}
return root;
}
第一根插入總是會工作得很好,但是當我嘗試添加:第二個,該計劃將賽格第二個呼叫到insert_student後故障。它未能在比較
if(root->student_name == NULL)
我懷疑是有事情做與我訪問根(根 - >子)的子節點,但我真的不知道是什麼。
p/s:我知道我沒有解除分配,這只是一個暫時的事情,因爲我需要使用不同的庫。
更新:刪除多餘的代碼。
是的,你說得對,它沒有失敗,我重新檢查,我相信它實際上在比較失敗(編輯我的文章反映)。我也刪除了臨時分配,這是假設我要刪除的其他東西。 – rlhh