linked list sorting

This is a discussion on linked list sorting within the C Programming forums, part of the General Programming Boards category; My task is to write a code which builds a list of candidates entered from command line & sort them ...

linked list sorting

My task is to write a code which builds a list of candidates entered from command line & sort them alphabetically on the fly with linked list.
The problem is if I put in the final loop
if (CandidatesList)
the program does not ever get to execute the function InsertAfter. It is InsertFirst all the way.
on the other hand if I put
if (CandidatesList->Next==NULL)
The first value in list get the InsertFirst, then all following values are in the order of input entered to the list- last on in list- first entered & not alphabetically manner.

Just one question. Why?
Actually two. Why do you have more than one insert function?
Ok, three. Why don't you just use one function to insert whever you need to?

Code:

void insert( Node **list, Node *instance )
{
ptr = *list;
if ptr->something comes after instance->something
add pointer to the end of instance and make the list start now be instance
else
while ptr->next exists, and ptr->next->something it comes after instance->something
move through the list
insert instance after ptr but before ptr->next, if there is in fact a ptr->next
}

I'll leave that as an exersize to the reader, but that's ideally how you should be doing your insertion.

2) "Node" is the generic term for an element in a list. In this case, "Node" would be a just like what you have it as, except I see that you're one of those wierd people who insist on typedef-ing pointers to their own type. So in your case you'd use:

Code:
void insert( Node **list, Node *instance )
{
ptr = *list;
if ptr->something comes after instance->something
add pointer to the end of instance and make the list start now be instance
else
while ptr->next exists, and ptr->next->something it comes after instance->something
move through the list
insert instance after ptr but before ptr->next, if there is in fact a ptr->next
}