Skip to content

147. Insertion Sort List

  • Time: $O(n^2)$
  • 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* insertionSortList(ListNode* head) {
    ListNode dummy(0);
    ListNode* prev = &dummy;  // the last and thus largest of the sorted list

    while (head != nullptr) {       // the current inserting node
      ListNode* next = head->next;  // Cache the next inserting node.
      if (prev->val >= head->val)
        prev = &dummy;  // Move `prev` to the front.
      while (prev->next && prev->next->val < head->val)
        prev = prev->next;
      head->next = prev->next;
      prev->next = head;
      head = next;  // Update the current inserting node.
    }

    return dummy.next;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public ListNode insertionSortList(ListNode head) {
    ListNode dummy = new ListNode(0);
    ListNode prev = dummy; // the last and thus largest of the sorted list

    while (head != null) {       // the current inserting node
      ListNode next = head.next; // Cache the next inserting node.
      if (prev.val >= head.val)
        prev = dummy; // Move `prev` to the front.
      while (prev.next != null && prev.next.val < head.val)
        prev = prev.next;
      head.next = prev.next;
      prev.next = head;
      head = next; // Update the current inserting node.
    }

    return dummy.next;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def insertionSortList(self, head: ListNode | None) -> ListNode | None:
    dummy = ListNode(0)
    prev = dummy  # the last and thus largest of the sorted list

    while head:  # the current inserting node
      next = head.next  # Cache the next inserting node.
      if prev.val >= head.val:
        prev = dummy  # Move `prev` to the front.
      while prev.next and prev.next.val < head.val:
        prev = prev.next
      head.next = prev.next
      prev.next = head
      head = next  # Update the current inserting node.

    return dummy.next