Leetcode

Insertion Sort List

  • Time:O(n^2)
  • Space:O(1)

C++

class Solution {
 public:
  ListNode* insertionSortList(ListNode* head) {
    ListNode dummy(0);
    ListNode* prev = &dummy;  // the last (largest) of the sorted list

    while (head) {                  // current inserting node
      ListNode* next = head->next;  // cache next inserting node
      if (prev->val >= head->val)   // `prev` >= current inserting node
        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 current inserting node
    }

    return dummy.next;
  }
};

JAVA

class Solution {
  public ListNode insertionSortList(ListNode head) {
    ListNode dummy = new ListNode(0);
    ListNode prev = dummy; // the last (largest) of the sorted list

    while (head != null) {       // current inserting node
      ListNode next = head.next; // cache next inserting node
      if (prev.val >= head.val)  // `prev` >= current inserting node
        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 current inserting node
    }

    return dummy.next;
  }
}

Python

class Solution:
  def insertionSortList(self, head: ListNode) -> ListNode:
    dummy = ListNode(0)
    curr = head

    while curr:
      prev = dummy
      while prev.next and prev.next.val < curr.val:
        prev = prev.next
      next = curr.next
      curr.next = prev.next
      prev.next = curr
      curr = next

    return dummy.next