Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list’s head.
Example:
Input: head = [4,2,1,3]
Output: [1,2,3,4]
Constraints:
[1, 5000]
.-5000 <= Node.val <= 5000
-5000 <= Node.val <= 5000
.[1, 5000]
.current
to traverse the list.prev
to point to the node before the insertion point in the sorted list.next
to temporarily store the next node in the original list during insertion.class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def insertionSortList(head: ListNode) -> ListNode:
if not head or not head.next:
return head
# Create a sentinel (dummy) node that will help in managing the sorted list
sentinel = ListNode(0)
sentinel.next = head
current = head.next
sentinel.next.next = None
while current:
# Keep the next node to process
next_to_process = current.next
# Insert the current node into the sorted part
prev = sentinel
next_sorted = sentinel.next
while next_sorted and next_sorted.val < current.val:
prev = next_sorted
next_sorted = next_sorted.next
# Current's insertion
current.next = next_sorted
prev.next = current
# Move to the next node
current = next_to_process
return sentinel.next
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?