Given the head
of a singly linked list, sort the list using insertion sort, and return the sorted list's head.
The steps of the insertion sort algorithm:
Example 1:
Input: head = [4,2,1,3]
Output: [1,2,3,4]
Example 2:
Input: head = [-1,5,3,4,0]
Output: [-1,0,3,4,5]
Constraints:
[1, 5000]
.-5000 <= Node.val <= 5000
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def insertion_sort_list(head):
dummy_head = ListNode(0)
dummy_head.next = head
current = head
while current and current.next:
if current.val <= current.next.val:
current = current.next
else:
node_to_insert = current.next
current.next = current.next.next
# Find the right place to insert
prev = dummy_head
while prev.next and prev.next.val < node_to_insert.val:
prev = prev.next
# Insert the node
node_to_insert.next = prev.next
prev.next = node_to_insert
return dummy_head.next
# Example usage (for testing):
# Helper function to create a linked list from a list
def create_linked_list(lst):
if not lst:
return None
head = ListNode(lst[0])
current = head
for val in lst[1:]:
current.next = ListNode(val)
current = current.next
return head
# Helper function to convert a linked list to a list
def linked_list_to_list(head):
lst = []
current = head
while current:
lst.append(current.val)
current = current.next
return lst
# Example 1
head1 = create_linked_list([4, 2, 1, 3])
sorted_head1 = insertion_sort_list(head1)
print(f"Example 1: {linked_list_to_list(sorted_head1)}")
# Example 2
head2 = create_linked_list([-1, 5, 3, 4, 0])
sorted_head2 = insertion_sort_list(head2)
print(f"Example 2: {linked_list_to_list(sorted_head2)}")
# Example 3: Empty list
head3 = create_linked_list([])
sorted_head3 = insertion_sort_list(head3)
print(f"Example 3: {linked_list_to_list(sorted_head3)}")
# Example 4: Single element list
head4 = create_linked_list([7])
sorted_head4 = insertion_sort_list(head4)
print(f"Example 4: {linked_list_to_list(sorted_head4)}")
# Example 5: Already sorted list
head5 = create_linked_list([1, 2, 3, 4, 5])
sorted_head5 = insertion_sort_list(head5)
print(f"Example 5: {linked_list_to_list(sorted_head5)}")
dummy_head
node is created to simplify insertion at the beginning of the list.current
pointer iterates through the list.current.val
is greater than current.next.val
, the node current.next
is removed and re-inserted into the sorted portion of the list.dummy_head
) and insert it.dummy_head.next
).dummy_head
, current
, prev
, node_to_insert
) are used.while current and current.next:
will immediately evaluate to false.if current.val <= current.next.val:
condition is always true, so the inner loop never executes, resulting in O(n) time complexity.