2016-01-30 163 views
-1

我有一个School struct持有链接列表Student struct s和这些Student struct s中的每一个持有链接列表Courses struct s。我对我如何能够释放这两个链表感到困惑。我特别不确定如何释放Courses链接列表,因为它位于另一个链接列表中。如何释放另一个链表中的链接列表?

struct Courses { 
    char *courseName; 
    int creditValue; 
    Courses *next; 
} Courses; 

struct Student { 
    char *studentName; 
    int studentAge; 
    Courses *coursesList; //First course (node) 
    Student *next; 
} Student; 

struct School { 
    char *schoolName; 
    int schoolAge; 
    Student *studentList; //First student (node) 
} School; 

如果有人能告诉我一个关于如何能够释放这两个链接列表的例子,那将是非常棒的!

+1

我想你应该花更多的时间来构建您的设计。为什么Student结构会持有指向下一个学生的指针? “下一个学生”甚至是什么意思?课程相同。在你修好这部分之后,你可能需要有一个额外的全球课程列表,你会在你处理完所有的学生后处理掉。 –

+1

你的工作在哪里完成? – Rabbid76

回答

3

你应该想到在所有权方面:当你释放一个项目,你必须释放所有它拥有,那就是一切他有一个指针指向未拥有别的东西

沿着这些线路,每个列表项拥有下一个项目,每一个School拥有Student的名单,每Student拥有其Courses名单。

您的类型定义看起来不正确,因为您对类型和变量使用相同的标识符。你应该重写它们是这样的:

typedef struct Course Course; 
typedef struct Student Student; 
typedef struct School School; 

struct Course { 
    char *courseName; 
    int creditValue; 
    Course *next; 
}; 

struct Student { 
    char *studentName; 
    int studentAge; 
    Course *courseList; //First course (node) 
    Student *next; 
}; 

struct School { 
    char *schoolName; 
    int schoolAge; 
    Student *studentList; //First course (node) 
}; 

的函数来释放一切:

void freeSchool(School *school) { 
    Student *student = school->studentList; 
    while (student) { 
     Course *course = student->courseList; 
     while (course) { 
      free(course->courseName); // if it was allocated 
      Course *nextCourse = course->next; 
      free(course); 
      course = nextCourse; 
     } 
     free(student->studentName); // if it was allocated 
     Student *nextStudent = student->next; 
     free(student); 
     student = nextStudent; 
    } 
    free(school->schoolName); // if it was allocated 
    free(school); 
} 

注意不同层次之间的相似性。您还可以将此功能拆分为单独的freeSchoolfreeStudentfreeCourse函数,您可以使用这些函数来处理程序中的单个对象删除。

一种优雅的方式来处理元素缺失则可能是freeXXX函数返回的下一个元素并释放节点:

Courses *freeCourse(Course *course) { 
    Course *next = course->next; 
    free(course->courseName); // if it was allocated 
    free(course); 
    return next; 
} 

Student *freeStudent(Student* student) { 
    Student *next = student->next; 
    while (student->courseList) { 
     student->courseList = freeCourse(student->courseList); 
    } 
    free(student->studentName); // if it was allocated 
    free(student); 
    return next; 
} 

School *freeSchool(School *school) { 
    while (school->studentList) { 
     school->studentList = freeStudent(school->studentList); 
    } 
    free(school->schoolName); // if it was allocated 
    free(school); 
    return NULL; 
} 
相关问题