Swift solution


  • 0
    class Solution {
        func insertionSortList(_ head: ListNode?) -> ListNode? {
            if head == nil {
                return nil
            }
            
            let dummy = ListNode(0)
            var cur: ListNode? = head
            var pre: ListNode? = dummy
            var next: ListNode? = nil
            
            while cur != nil {
                next = cur?.next
                while pre?.next != nil && pre!.next!.val < cur!.val {
                    pre = pre?.next
                }
                cur?.next = pre?.next
                pre?.next = cur
                pre = dummy
                cur = next
            }
            
            return dummy.next
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.