Given a linked list, change it to be in sorted order

Write a function which given a list, rearranges its nodes so they are sorted in increasing order.


 


 

The idea is to use SortedInsert() from previous post. We start with an empty result list. Iterate through the source list and SortedInsert() each of its nodes into the result list. Be careful to note the .next field in each node before moving it into the result list.

 
C++ implementation –
 

Download   Run Code

Output:

2 -> 3 -> 4 -> 6 -> 8 -> 9 -> null

 

 
Source:
http://cslibrary.stanford.edu/105/LinkedListProblems.pdf

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz