我试图用下面的结构创建学生的链表。学生结构的链表实现
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