Simple Java recursive solution


  • 1
    M
    public ListNode insertionSortList(ListNode head) {
        if(head == null) return null;
        else if(head.next == null) return head;
        ListNode p = head, q = insertionSortList(head.next), pre = p, dummy = q;
        p.next = q;
        if(p.val <= q.val){
            return p;
        }else{
            while(q != null && p.val > q.val){
                q = q.next;
                pre = pre.next;
            }
            pre.next = p;
            p.next = q;
            return dummy;   
        }
    }

Log in to reply
 

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