Hey all,
I'm having a trouble with this code, which supposed to get names of students and their grades, determine fail students and passed, sort the names in lexicographical order and then prints two lists of failed and passed students... if you have any clue about fixing it I'll be more than glad! thank you.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NAME_SIZE 30
typedef struct student_node
{
char name[MAX_NAME_SIZE];
double grade;
struct Student* next;
} Student;
void free_mem(Student *head)
{
if (head == NULL)
return;
free_mem(head->next);
free(head);
}
Student *read_students()
{
char name[MAX_NAME_SIZE];
double grade;
Student *head = NULL, *nstd = NULL;
printf("Enter name:\n");
scanf("%s",&name);
while (strcmp(name, "exit")!= 0)
{
printf("Enter grade:\n");
scanf("%lf", &grade);
nstd = (Student*) malloc (sizeof(Student));
if (nstd == NULL)
{
printf("Fatal error: memory allocation failed!\n");
return 0;
}
strcpy(nstd->name, name);
nstd->grade = grade;
nstd->next = head;
head = nstd;
printf("Enter Name:\n");
scanf("%s",name);
}
return head;
}
void print_list(Student *pHead)
{
Student* list;
for (list = pHead; list != NULL; list = list->next)
printf("\n%s %g\n", list->name, list->grade);
return;
}
void split_list(Student *pHead, Student** pass, Student** fail)
{
Student* list= pHead;
Student *passed_student = NULL;
Student *failed_student = NULL;
Student* buffer=pHead;
while(list!=NULL)
{
buffer=list->next;
if (list->grade >= 60)
{
list->next = *pass;
*pass = list;
}
if (list->grade < 60)
{
list->next = *fail;
*fail = list;
}
list = buffer;
}
}
Student *sort_list(Student **pHead)
{
Student* buffer=NULL, *list=*pHead, *last=NULL, *tmp=*pHead, *first=*pHead;
if(first==NULL)
return;
while(first->next!=last)
{
for(list=first;list->next!=last;list=list->next)
{
if((strcmp(list->name, list->next->name)>0) && (list == first))
{
buffer=list->next;
first->next=buffer->next;
buffer->next=list;
first=buffer;
list=buffer;
}
else
{
buffer=list->next;
tmp->next=buffer;
list->next=buffer->next;
buffer->next=list;
list=buffer;
}
tmp=list;
}
last=tmp->next;
}
if(strcmp(first->name, first->next->name)>0)
{
buffer=list->next;
first->next=buffer->next;
buffer->next=list;
first=buffer;
list=buffer;
}
*pHead=first;
return 0;
}
int main()
{
Student *head = read_students();
Student *pass_list=NULL, *fail_list=NULL;
split_list(head, &pass_list, &fail_list);
sort_list(&pass_list);
sort_list(&fail_list);
printf("The Student that passed the test are\n");
print_list(pass_list);
printf("The Student that failed the test are\n");
print_list(fail_list);
free_mem(head);
free_mem(pass_list);
free_mem(fail_list);
return 0;
}
the problem is in the sort_list function....