![]() |
VOOZH | about |
Given a non-decreasing linked list. The task is to square the elements of the linked list and arrange them in sorted order without using any extra space.
Examples:
Input: 1->2->3->4->5
Output: 1->4->9->16->25Input: (-2) -> (-1) -> 0 -> 1 -> 2
Output: 0 ->1 -> 1 -> 4 -> 4
For Arrays: The problem to do the same for Arrays is discussed in this article - Sort array after converting elements to their squares
Approach: The task can be solved by partitioning the given list into two different linked lists from the point of transition (negative to positive), one containing only negative elements say 'l1' and the other containing positive elements say 'l2'. Square all the elements of the list l1 and reverse it and also square all the elements of list l2, now merge the two sorted lists to get the resultant list.
Below is the implementation of the above approach :
1 4 9 16 25
Time complexity: O(N), N is the number of nodes
Auxiliary space: O(1)