2016-01-30 83 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; 
} 
相關問題