【问题标题】:How to free linked list which is within another linked list?如何释放另一个链表中的链表?
【发布时间】:2016-01-30 19:59:57
【问题描述】:

我有一个School struct,它包含一个Student structs 的链接列表,每个Student structs 都拥有一个Courses structs 的链接列表。我对如何释放两个链表感到有些困惑。我特别不确定如何释放 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;

如果有人可以向我展示一个如何释放两个链接列表的示例,那就太好了!

【问题讨论】:

  • 我认为你应该花更多的时间来构建你的设计。为什么 Student 结构会保存指向下一个学生的指针? “下一个学生”是什么意思?课程也一样。修复此部分后,您可能需要额外的全球课程列表,您将在处置所有学生后处置。

标签: c struct linked-list free


【解决方案1】:

你应该从所有权的角度来考虑:当你释放一个物品时,你必须释放它拥有的所有东西,也就是他有一个指针指向但不拥有的所有东西用别的东西。

沿着这些线,每个列表项拥有下一项,每个School拥有它的Students列表,每个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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-08
    • 2013-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-18
    • 1970-01-01
    • 2011-06-26
    相关资源
    最近更新 更多