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.
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).
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.
- Merge a linked list into another linked list at alternate positions
- Know Your Sorting Algorithm | Set 1 (Sorting Weapons used by Programming Languages)
- Know Your Sorting Algorithm | Set 2 (Introsort- C++’s Sorting Weapon)
- Sorting objects using In-Place sorting algorithm
- Delete alternate nodes of a Linked List
- Reverse alternate K nodes in a Singly Linked List
- Given a linked list, reverse alternate nodes and append at the end
- Rearrange a linked list in to alternate first and last element
- Print alternate nodes of a linked list using recursion
- Print the alternate nodes of linked list (Iterative Method)
- Alternate Odd and Even Nodes in a Singly Linked List
- Product of the alternate nodes of linked list
- Sum of the alternate nodes of linked list
- Reverse alternate K nodes in a Singly Linked List - Iterative Solution
- Subtraction of the alternate nodes of Linked List
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- Check if a linked list is Circular Linked List
- Convert singly linked list into circular linked list
- Difference between Singly linked list and Doubly linked list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.