Sort Linked List Already Sorted Using Absolute Values Problem
Description
LeetCode Problem 2046.
Given the head of a singly linked list that is sorted in non-decreasing order using the absolute values of its nodes, return the list sorted in non-decreasing order using the actual values of its nodes.
Example 1:

Input: head = [0,2,-5,5,10,-10]
Output: [-10,-5,0,2,5,10]
Explanation:
The list sorted in non-descending order using the absolute values of the nodes is [0,2,-5,5,10,-10].
The list sorted in non-descending order using the actual values is [-10,-5,0,2,5,10].
Example 2:

Input: head = [0,1,2]
Output: [0,1,2]
Explanation:
The linked list is already sorted in non-decreasing order.
Example 3:
Input: head = [1]
Output: [1]
Explanation:
The linked list is already sorted in non-decreasing order.
Constraints:
- The number of nodes in the list is the range
[1, 10^5]. -5000 <= Node.val <= 5000headis sorted in non-decreasing order using the absolute value of its nodes.
Follow up:
- Can you think of a solution with
O(n)time complexity?
Solution
Approach: Move negatives to the front
The list is sorted by absolute value, so the non-negative nodes are already in increasing order, and the negative nodes appear in decreasing order. Walking through the list, every time we meet a negative node we cut it out and put it in front of the head. Each negative node then lands before the ones that came earlier, which have a larger value, and all of them stay before the non-negative nodes.
The time complexity is O(n) and the space complexity is O(1), where n is the length of the list.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def sortLinkedList(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev, curr = head, head.next
while curr:
if curr.val < 0:
t = curr.next
prev.next = t
curr.next = head
head = curr
curr = t
else:
prev, curr = curr, curr.next
return head