LeetCode Solutions
147. Insertion Sort List
Time: $O(n^2)$ Space: $O(1)$
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;
}
};
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;
}
}
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