我正在对链表进行一些练习,这些是结构。
typedef struct roomList roomList;
typedef struct school school;
typedef struct studentList studentList;
roomList *getRoom(school* school, int class, int roomNr);
struct studentList{
char *name;
int class;
float grade;
int roomNr;
studentList *next;
studentList *prev;
};
struct roomList{
int nrOfStudents;
int roomNr;
studentList *students; //pointer to student list.
roomList *next;
roomList *prev;
};
struct school{
int totalStudents;
roomList *Class[13]; //array of classes, each index contains rooms.
};
这是发生无限循环的地方,它是打印房间内所有学生的功能。
void printRoom(school *school, int class, int roomNr)
{
roomList *room = getRoom(school, class, roomNr);
studentList *student;
if(room != NULL)
{
int i = 1;
printf("Nr of students: %d\n", room->nrOfStudents);
while(room->nrOfStudents != 0 && student != NULL)
{
student = room->students;
printf("%d - \"%s\" ",i, student->name);
student = student->next;
i++;
}
}
}
这就是我创建student
studentList *createStudent(int class, char *name, int roomNr)
{
studentList *newNode;
newNode = (studentList*)calloc(1, sizeof(studentList));
newNode->class = class;
newNode->name = (char*)malloc(strlen(name)+1);
strcpy(newNode->name, name);
newNode->roomNr = roomNr;
newNode->grade = 0;
newNode->next = newNode->prev = NULL;
return newNode;
}
最后,这就是我将student
插入room
的方式。
void insertStudentToRoom(school* school, int class, int roomNr, char *name)
{
roomList *room;
room = getRoom(school, class, roomNr);
studentList *newStudent;
newStudent = createStudent(class, name, roomNr);
if(room->students != NULL)
{
newStudent->next = room->students;
room->students->prev = newStudent;
room->students = newStudent;
room->nrOfStudents++;
school->totalStudents++;
}
else
{
room->students = newStudent;
room->nrOfStudents++;
school->totalStudents++;
}
}
无限无限循环仅在我将多个student
插入room
时发生,而在只有一个学生的情况下可以退出,我尝试过{{ 1}}无济于事。
答案 0 :(得分:1)
while(room->nrOfStudents != 0 && student != NULL)
{
student = room->students;
printf("%d - \"%s\" ",i, student->name);
student = student->next;
i++;
}
仔细观察。您永远不会在循环中更改room
。因此,student = room->students;
将在循环中每次设置student
的值。如果它在第一次之后没有破裂,就不会再破裂了。
您可能希望将student = room->students;
移出循环。您只想指向房间中的第一个学生。