Given a Linked List. The Linked List is in alternating ascending and descending orders. Sort the list efficiently.
Input List: 10->40->53->30->67->12->89->NULL Output List: 10->12->30->43->53->67->89->NULL
A Simple Solution is to use Merge Sort for linked List. This solution takes O(n Log n) time.
An Efficient Solution works in O(n) time. Below are all steps.
1. Separate two lists.
2. Reverse the one with descending order
3. Merge both lists.
Below are the implementations of above algorithm.
Given Linked List is 10 40 53 30 67 12 89 Sorted Linked List is 10 12 30 40 53 67 89
Thanks to Gaurav Ahirwar for suggesting this method.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Sort Matrix in alternating ascending and descending order rowwise
- Sort a k sorted doubly linked list
- Sort linked list which is already sorted on absolute values
- Sort first half in ascending and second half in descending order | Set 2
- Sort first half in ascending and second half in descending order | 1
- Sort all even numbers in ascending order and then sort all odd numbers in descending order
- Sort first k values in ascending order and remaining n-k values in descending order
- Alternating split of a given Singly Linked List | Set 1
- Recursive approach for alternating split of Linked List
- Insertion sort to sort even and odd positioned elements in different orders
- Merge K sorted Doubly Linked List in Sorted Order
- Insert value in sorted way in a sorted doubly linked list
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
- Given a linked list which is sorted, how will you insert in sorted way
- PHP | Sort array of strings in natural and standard orders
- Sorting rows of matrix in ascending order followed by columns in descending order
- Sorting rows of matrix in descending order followed by columns in ascending order
- Sorted Linked List to Balanced BST
- Merge two sorted linked list without duplicates
- Sorted insert for circular linked list