列出链表的内容

时间:2017-10-24 21:40:38

标签: c linked-list

我需要写一个功能:不能改变功能! `void list_courses()列出了所有学生按顺序注册的所有课程编号。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

你说我们不应该改变函数void list_courses(),但你必须在某个地方struct student *开始迭代所有学生和所有课程。你似乎有一个静态变量的初始学生,我会假设你以某种方式填充该静态变量。以下是我将如何做到这一点:

static struct student *my_student;

void list_courses(){

    struct student *current_student = my_student;
    struct course *current_course;

    // Iterate over all students
    while(current_student != NULL){
        current_course = current_student->courses;

        // do something with the current student if needed ...

        // Iterate over courses of this student
        while(current_course != NULL){

            // do something with current course ...

            // Advance to the next course of this student
            current_course = current_course->next;
        }

        // Advance to the next student
        current_student = current_student->next;
    }
}

这段代码可能更紧凑,但为了清晰起见我做了一个冗长的版本。