sorting in linked list

This is a discussion on sorting in linked list within the C Programming forums, part of the General Programming Boards category; can someone give me an idea how i will create a sorting function for the linked list.. m pasting the ...

sorting in linked list

can someone give me an idea how i will create a sorting function for the linked list.. m pasting the code for my insert function of the linked list. i just want to know the logic of how i will sort the numbers as the user enters them.
thanks..

If you are going to sort the items as you insert them, you just need to search for the correct spot and insert there. If none of the items in the list are less than the new item, insert the new item at the tail.

I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.

I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.

but suppose i want to insert a value between to nodes... how will i tell my pointer to go 1 step back to insert a new node between those two?

For a doubly linked list, you use the "prev" pointer to get the previous node. If the list is singly linked, the general pattern is this:

Code:

node *prev, *curr;
prev = NULL;
curr = list;
if(curr)
{
if(!found(curr))
{
prev = curr;
for(curr = prev->next; curr; curr = curr->next)
{
if(found(curr))
{
break;
}
prev = curr;
}
}
if(curr)
{
/* Found it. At this point, prev points to the previous node, curr to the current node.
* If prev is NULL, the node which was found is at the head of the list, and you may
* have to handle that case specially.
*/
/* Do whatever you need to do here */
}
}
if(!curr)
{
/* Never found it. */
}

In this example, the found() function determines which node to stop at. The if(curr) followed by if(!curr) might seem redundant, but if you try to code it otherwise you will find that you have to duplicate the "never found it" code.