你應該想到在所有權方面:當你釋放一個項目,你必須釋放所有它擁有,那就是一切他有一個指針指向未擁有別的東西。
沿着這些線路,每個列表項擁有下一個項目,每一個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);
}
注意不同層次之間的相似性。您還可以將此功能拆分爲單獨的freeSchool
,freeStudent
和freeCourse
函數,您可以使用這些函數來處理程序中的單個對象刪除。
一種優雅的方式來處理元素缺失則可能是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;
}
我想你應該花更多的時間來構建您的設計。爲什麼Student結構會持有指向下一個學生的指針? 「下一個學生」甚至是什麼意思?課程相同。在你修好這部分之後,你可能需要有一個額外的全球課程列表,你會在你處理完所有的學生後處理掉。 –
你的工作在哪裏完成? – Rabbid76