Skip to content

2046. Sort Linked List Already Sorted Using Absolute Values 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  ListNode* sortLinkedList(ListNode* head) {
    ListNode* prev = head;
    ListNode* curr = head->next;

    while (curr != nullptr)
      if (curr->val < 0) {
        prev->next = curr->next;
        curr->next = head;
        head = curr;
        curr = prev->next;
      } else {
        prev = curr;
        curr = curr->next;
      }

    return head;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public ListNode sortLinkedList(ListNode head) {
    ListNode prev = head;
    ListNode curr = head.next;

    while (curr != null)
      if (curr.val < 0) {
        prev.next = curr.next;
        curr.next = head;
        head = curr;
        curr = prev.next;
      } else {
        prev = curr;
        curr = curr.next;
      }

    return head;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def sortLinkedList(self, head: ListNode | None) -> ListNode | None:
    prev = head
    curr = head.next

    while curr:
      if curr.val < 0:
        prev.next = curr.next
        curr.next = head
        head = curr
        curr = prev.next
      else:
        prev = curr
        curr = curr.next

    return head