Sort Linked List Based on Actual Values

Given a Singly Linked List of integers that are sorted based on their absolute values, the task is to sort the linked list based on the 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:

Input:
{1 -> -2 -> 3}
Output:
{-2 -> 1 -> 3}

Input:

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:

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.

Constraints:

  • 1 <= T <= 10
  • 1 <= 'N' <= 5 * 104
  • -109 <= 'data' <= 109 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
Note :
You don't need to print the output, it has already been taken care of. Just implement the given function.
AnswerBot
4mo

Sort a Singly Linked List based on actual values instead of absolute values.

  • Traverse the linked list and store the values in an array.

  • Sort the array based on actual values.

  • Update the linked list with ...read more

Help your peers!
Select
Add answer anonymously...

Popular interview questions of Software Engineer

A Software Engineer was asked Q1. Triplets with Given Sum Problem Given an array or list ARR consisting of N integ...read more
A Software Engineer was asked Q2. Remove Nodes with Specific Value from Linked List You are provided with a singly...read more
A Software Engineer was asked Q3. Sort Linked List Based on Actual Values Given a Singly Linked List of integers t...read more
Freshworks Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2025 Info Edge (India) Ltd.

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits