You are given a Singly Linked List of integers which is sorted based on absolute value.
You have to sort the Linked List based on actual values.
The absolute value of a real number x, denoted |x|, is the non-negative value of x without regard to its sign.
Example:
If the given list is {1 -> -2 -> 3} (which is sorted on absolute value), the returned list should be {-2 -> 1 -> 3}.
Input Format:
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 line of each test case contains the elements of the singly linked list separated by a single space and terminated by -1. Hence, -1 would never be a list element.
It is guaranteed that the given list is sorted based on absolute value.
Output Format:
For each test case, print the sorted linked list. The elements of the sorted list should be single-space separated, terminated by -1.
The output of each test case is printed in a separate line.
Note :
You don't need to print the output, it has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 10
1 <= 'N' <= 5 * 10^4
-10^9 <= 'data' <= 10^9 and 'data' != -1
Where 'N' denotes the number of elements in the Singly Linked List and 'data' represents the value of those elements.
Time Limit : 1 sec
Use 2 pointers: fast and slow to divide the list into 2 sublist: list1 and list2 and make sure list1 is equal to or is longer than list2.
The key is the condition of while loop while(fast.next!=null &&...read more
We will use the ‘Insertion Sort’ algorithm to sort the given linked list.
Algorithm:
We will make a list ‘SORTED_LIST’ which is initially empty and it stores the list after sorting.
We wi...read more
We will use the ‘Merge Sort’ algorithm to sort the given linked list. Merge Sort is a Divide and Conquer algorithm. In this algorithm, we will divide the list into two parts, recursively sor...read more
In the given list all non-negative values are present in sorted order but all negative values are present in reverse order. We have to reverse the negative values and move it be...read more
Top Freshworks Software Engineer interview questions & answers
Popular interview questions of Software Engineer
Reviews
Interviews
Salaries
Users/Month