-
sorting a linked list
What is the proper way to sort a linked list. This was all I could think up.
Code:
int change = 1;
while ( change )
{
change = 0;
current = start;
next = current->next;
do
{
if ( current->data > next->data)
{
swapping code goes here;;;
change=1;
}
current = current->next;
next = current->next;
} while ( current->next );
}
-
And what would you think that you should do?
I can think of two solutions:
Swap places within the linked list (you need to know the previous link for that, so that you can update the next pointer of the previous node)
Swap the actual data.
Sorting linked lists is often best done by creating a new list by insertion sorting the new list.
--
Mats
-
This is what I have for the swap code.
Code:
int change = 1;
char word[80];
while ( change )
{
change = 0;
current = start;
next = current->next;
do
{
if ( strcmp(current->word, next->word) > 0 )
{
strcpy(word, current->word);
strcpy(current->word, next->word);
strcpy(next->word, word);
change=1;
}
current = current->next;
next = current->next;
} while ( current->next );
}
-
I just have never done this before. Linked list are still new to me. So if it works. it is correct :-)
-
Seeing as you have (potentially) rather long strings, you may want to recreate the list instead by removing the element from the original list, and placing it in a new fresh list [at the right place, of course].
--
Mats