Sunday, August 2, 2009

Balance a Linked List in C++?

How do I balance a linked list in C++?





To balance, I mean sorting the nodes in the list so that the node with the greatest value is at the head of the list, the second greatest node is at the end, and so on... (the data type is double)





Thanks for you help!!!

Balance a Linked List in C++?
No, he/she means this I believe:





100 98 96 95 97 99





As for how to do this...interesting question. One thought is to take the original list and sort it:





100 99 98 97 96 95





Then take a pass through, skipping every other element until the middle:





100 98 96





Then make a second pass in the opposite direction:





95 97 99





Glue these two lists together.
Reply:So you don't really mean "balance" but rather simply "sort" in descending order. Correct?





Once the list is created (or manipulated) you need a sort routine to quickly sort it. If the list will be large, like in the thousands of nodes level, then create a quicksort routine. (Search the web for libraries or code - many exist).





Otherwise, just code up a simple exchange sort for smaller lists.


No comments:

Post a Comment