2012-09-30 83 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,然后才能访问它们。