Alternate sorting of Linked list
Given a linked list containing n nodes. The problem is to rearrange the nodes of the list in such a way that the data in first node is first minimum, second node is first maximum, third node is second minimum, fourth node is second maximum and so on.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input : list: 4->1->3->5->2 Output : 1->5->2->4->3 Input : list: 10->9->8->7->6->5 Output : 5->10->6->9->7->8
Approach: Following are the steps:
- Sort the linked list using Merge Sort technique.
- Split the list into front and back lists. Refer FrontBackProcedure of this post.
- Now, reverse the back list. Refer this post.
- Finally, merge the nodes of first and back lists in alternate order.
Original list: 10 9 8 7 6 5 Modified list: 5 10 6 9 7 8
Time Complexity: O(n*logn).