You are 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 <= The length of the list <= 5000.-5000 <= Node.val <= 5000# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
arr = []
cur = head
while cur:
arr.append(cur.val)
cur = cur.next
arr.sort()
cur = head
for val in arr:
cur.val = val
cur = cur.next
return head# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
cur = head.next
while cur:
tmp = head
while tmp != cur:
if tmp.val > cur.val:
tmp.val, cur.val = cur.val, tmp.val
tmp = tmp.next
cur = cur.next
return head# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def insertionSortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(0, head)
prev, cur = head, head.next
while cur:
if cur.val >= prev.val:
prev, cur = cur, cur.next
continue
tmp = dummy
while cur.val > tmp.next.val:
tmp = tmp.next
prev.next = cur.next
cur.next = tmp.next
tmp.next = cur
cur = prev.next
return dummy.next