2012-09-30 28 views
0

我試圖用下面的結構創建學生的鏈表。學生結構的鏈表實現

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:我知道我沒有解除分配,這只是一個暫時的事情,因爲我需要使用不同的庫。

更新:刪除多餘的代碼。

回答

1

找到確切的問題有點難,我們不知道如何調用這個函數。似乎有一些你想檢查的東西。

我假設你傳遞給函數的childroot確實分配,與根的所有字段設置爲NULL和學生的名字是爲了讓你的第二個分支永遠不會發生。然後,第一次插入將工作。

但是,當你做第二次插入。您正在通過root->child,您在第一個if子句中設置爲NULL。這將導致後續strcmp失敗,因爲您無法從NULL取消引用(例如NULL->student_name會引發錯誤)。

0

當您遞歸調用insert_student時,應確保您傳遞的值爲root不爲空。你可能需要另一種情況,如果它是空的(如插入結束)。

我注意到的一件事是,你從不使用temp的分配值。在使用temp之前,它始終未被使用或丟棄。我假設這不是你想要的。

而且,通常這個詞next將被用來代替的結構和類似的東西newStudentchild只是student,而不是孩子的參數。

+0

是的,你說得對,它沒有失敗,我重新檢查,我相信它實際上在比較失敗(編輯我的文章反映)。我也刪除了臨時分配,這是假設我要刪除的其他東西。 – rlhh

0
if(root->student_name == NULL) 
{ 
    printf("Always here?\n"); 
    root->student_ID = child->student_ID; 
    root->student_name = strdup(child->student_name); 
    temp->student_ID = 0; 
    temp->student_name = NULL; 
    root->child = temp; 
} 

我發現我實際上需要聲明子節點的變量爲NULL,然後才能訪問它們。