2 minutes
Leetcode 2046
2046. Sort Linked List Already Sorted Using Absolute Values
The idea of this solution is to check whether the current value is smaller than 0. If so, we can remove it from its current position, add it to the beginning of the list, and make that the new beginning.
This solution works because the absolute value of -1 will always be smaller than the absolute value of -5, but -1 is greater than -5. So if we have the linked list [-1, -5], we can go through the linked list from the 0 index to the end, find the greatest valued negative numbers, and add them to the beginning before the smaller negative numbers.
The idea of this solution can be shown using the following image:

- Step one is initializing the start, prev, andcurvariables.- startis the very beginning of the linked list. In this example,- 0is the head. Notice how- startis always the beginning of the linked list while the head isn’t always.
- curis the current value we are on. We can initialize it at position- 1(0 Indexed) because if position- 0is negative, it is the greatest negative number, and we don’t have to worry. And if the value at position- 0is positive, it is the smallest positive value, and all the negative values that we add before it will always be smaller.
- previs always the node before- curso we can check whether- cur.Valis negative and remove the node from the linked list.
 
- In step 2, we have moved prevandcurup by one node.
- In step three, we move prevandcurup by one more node.
- In step 4, we can see that cur is negative. So we can remove it from the list and add another ListNodewith the same value to the beginning. We makestartequal to this newListNodebecause that is the new start of the linked list.
- In step 5, we can see that cur is negative, so we can do the same thing as step 4.
- In step 6, we move curandprevup by a node, butcur == nil, so we break out of the loop and returnstart.
func sortLinkedList(head *ListNode) *ListNode {
    cur := head.Next
    prev := head
    start := head
    
    for cur != nil {
        if cur.Val < 0 {
            start = &ListNode{ cur.Val, start }
            cur = cur.Next
            prev.Next = prev.Next.Next
        } else {
            prev = prev.Next
            cur = cur.Next
        }
    }
    
    return start
}
Read other posts