on the line where I have:
trailing = current = student;
does it mean that prev and next of trailing and current will be automatically set to prev and next of student?
I am pasting the code more clearly...sorry
Code:
int LoadDatabase(Database *dBase)
{
FILE *f;
StudentRecord *student, *trailing=NULL, *current=NULL;
int i=0;
f = fopen("Database.txt","r"); // check if the file has open properly
if(f == NULL) {
printf("Cannot open that file");
return -1;
}
/* unarchive all the students and put them in the list */
while ( (student = UnarchiveStudent(f) )!= NULL)
{
if(current == NULL) //if the list is empty
{
dBase->students = student;
student->prev = student->next = NULL;
trailing = current = student;
}
else if ( (current != NULL) && ( (current->next) == NULL) ) /*if there is only one node in the list*/
{
if (strcmp(student->sLastName, current->sLastName) > 0) /*insert after that single node*/
{
student->next = NULL;
student->prev = current;
current->next = student;
}
else /*insert before that single node, right after the head*/
{
student->next = current;
student->prev = NULL;
dBase->students = student;
current->prev = student;
trailing = current = student;
}
}
else /*if the list already consists of many nodes*/
{
while(1)
{
if (strcmp(student->sLastName, current->sLastName) > 0) //if the name is still >, keep going along the list
{
trailing = current;
current = current->next;
}
//the node has to be inserted now !!!
else if (trailing == current ) //if we have to insert in the beginning, right after the head
{
student->next = current;
student->prev = NULL;
current->prev = student;
dBase->students = student;
break;
}
else if ( (current->next) != NULL)//if the end of the list hasn't been reached yet,insert before the current position and after trailing */
{
student->next = current;
student->prev = trailing;
trailing->next = student;
current->prev = student;
break;
}
else /*if the insertion has to be performed at the end of the list*/
{
student->next = NULL;
student->prev = current;
current->next = student;
break;
}
}
//move back trailing and current to the beginning of the list in the right order
current = trailing = dBase->students;
trailing->prev = current->prev = NULL;
}
i++;
}
(dBase->studentCount) = i;
fclose(f);
return 0;
}