VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sort-a-linked-list-after-converting-elements-to-their-squares/

⇱ Sort a linked list after converting elements to their squares - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sort a linked list after converting elements to their squares

Last Updated : 23 Jul, 2025

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->25

Input: (-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 :


Output
1 4 9 16 25 

Time complexity: O(N), N is the number of nodes
Auxiliary space: O(1) 

Comment
Article Tags: