# 为什么这里有无限循环？ （链接列表打印）

[英]Why is there an infinite loop here? (linked list printing)

``````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;
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++;
}
}
}

``````

``````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->next   = newNode->prev = NULL;

return newNode;
}
``````

``````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++;
}
}
``````

``````    while(room->nrOfStudents != 0 && student != NULL)
{
student = room->students;
printf("%d - \"%s\" ",i, student->name);
student = student->next;
i++;
}
``````