
Biotonic Doubly linked list is the one which is first increasing and then decreasing. A strictly increasing or strictly decreasing doubly linked list is also biotonic.
The first line of input contains a single integer T, representing the number of test cases or queries to be run.
Then the T test cases follow.
The first and the only line of every test case contains the elements of the doubly linked list separated by a single space and terminated by -1. Hence, -1 would never be a list element.
For each test case, print the sorted doubly linked list.
The output of each test case is printed in a separate line.
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 5 * 10^4
-10^9 <= data <= 10^9 and data != -1
Where T is the number of test cases, N is the length of the doubly linked list.
Time Limit : 1sec
The main idea is to store the values of all nodes in a list and then sort that list. After that create a doubly-linked list of N size where N is the size of the list and the value of ith node from left is ith value in a list from i equal to 1 to N.
We will use the ‘Merge Sort’ algorithm to sort the given doubly linked list. Merge Sort is a Divide and Conquer algorithm. In this algorithm, we will divide the list into two parts, recursively sort the two parts and finally merge them such that the resultant list will be sorted.
The above operation will ensure that mid will point to the middle node of the list. ‘mid’ will be the head of the second sublist, so we will change the ‘next’ value of the node which is before mid to NULL.
One way is to find the first node in the doubly linked list which is smaller than its previous node and let it be current. If no such node is present then the list is already sorted.
Split the list into two parts, one from head to node just before the current node and another from current node to the end node.Then reverse the second sub-list starting from current node to the end. Now merge these two sorted lists and return the merged list.
The idea is to take two pointers, one pointing at the head node of the list and another pointing at the last node of the list. Now compare the values of these two nodes and add the smaller node to the result list. Then advance the pointer of the smaller node. Repeat the above process until all the nodes of the list are processed.