Appearance
Approach: Dummy head for the sorted prefix; take each next node and insert it into the correct position in the sorted list.
Complexity: O(n²) time, O(1) space
go
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func insertionSortList(head *ListNode) *ListNode {
dummy := &ListNode{}
curr := head
for curr != nil {
next := curr.Next
prev := dummy
for prev.Next != nil && prev.Next.Val < curr.Val {
prev = prev.Next
}
curr.Next = prev.Next
prev.Next = curr
curr = next
}
return dummy.Next
}