Hi i am writing a program that manage a list of student, i am using a list, each element is described like this:
struct student
{
char lastname[50];
char name[50];
char date_of_birth[50];
char height[50];
struct student *next;
};
struct student *root=0; //this is the root node
This is how i add element to the list:
void add_element(struct student **root, char lastname[50], char name[50], char date_of_birth[50], char height[50])
{
if(*root == 0)
{
*root = malloc(sizeof(struct student));
strcpy((*root)->lastname,lastname);
strcpy( (*root)->name,name);
strcpy( (*root)->date_of_birth,date_of_birth);
strcpy( (*root)->height,height);
(*root)->next = 0;
}
else
{
add_element(&(*root)->next,lastname,name,date_of_birth,height);
}
}
I also wrote 2 function, one is for reading from a file, the other is to write the file, the file contains all the students, everything works but i need a function to sort all the element in alphabetical order by lastname, i tried to write one, but it doesn't work, it keeps crashing.
I tried a lot of things and they didn't work, this is one attempt, and it doesn't work :-(
please help me
void sort(struct student *head)
{
struct student **current;
struct student *tmp;
for(current = &head ; *current !=NULL ; current = (*current)->next)
{
if((*current)->next == NULL)
{
break;
}
switch(strcmp((*current)->lastname,(*current)->next->lastname))
{
case 0:
{
printf("user not valid");
break;
}
case 1:
{
tmp = *current;
*current = (*current)->next;
(*current)->next = tmp;
break;
}
}
}
}
After including remarks from comments to correct the proposed source code, the algorithm to sort the linked-list is missing some steps. At least, to sort a linked-list, it is necessary to have two loops. The choice used of a
struct student **current
access will be complex for a two nested loops.Here is another powerful sorting function using the optimized
qsort()
function.Step 1 - before showing the function, to sort a list, the
root
pointer shall be modified.Step 2 - the function
sort()
usingqsort()
quicksort function.The method allocates a temporary array of pointers in order to have a fixed-size element to be sorted.
struct student *
, fill the array by using a loop to each item of the linked-list;qsort()
function by using the customized comparison functionnode_compare()
(see next step);struct student *next
(the first is*root
and the last is pointing to NULL).struct student *
;That's all.
Step 3 - the comparison function
node_compare()
needed toqsort()
.Enhancement - because the
add_element()
is using a recursive call not compliant with a long linked-list, here is a quite simple non-recursive algorithm.