Simple Java Solution No comments required


  • 0
    public ListNode insertionSortList(ListNode head) {
            if(head==null || head.next==null) return head;
            
            ListNode prev = head;
            ListNode curr = head.next;
            
            while(curr != null){
                ListNode next = curr.next;
                
                curr.next = null;
                prev.next = next;
                
                ListNode temp = head;
                if(temp.val>=curr.val){
                    curr.next = temp;
                    head = curr;
                } else {
                    while(temp.next!=null && temp.next!=next){
                        if(temp.next.val >= curr.val){
                            curr.next = temp.next;
                            temp.next = curr;
                            break;
                        } else temp = temp.next;
                    }
                    
                    if(curr.next==null){
                        curr.next = next;
                        prev.next = curr;
                        prev = curr;
                    }
                }
                
                curr = next;
            }
            return head;
        }
    

Log in to reply
 

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