Java clean solution beats 98%


  • 0
    T
    public class Solution {
        public ListNode insertionSortList(ListNode head) {
            if (head == null || head.next == null) {
                return head;
            }
    
            ListNode dummy = new ListNode(Integer.MIN_VALUE), tail = dummy;
    
            while (head != null) {
                ListNode temp = head.next;
                if (head.val >= tail.val) {
                    tail.next = head;
                    tail = tail.next;
                    head.next = null;
                } else {
                    insert(dummy, head);
                }
                head = temp;
            }
    
            return dummy.next;
        }
    
        private void insert(ListNode dummy, ListNode head) {
            ListNode cur = dummy;
    
            while (cur.next.val < head.val) {
                cur = cur.next;
            }
    
            ListNode temp = cur.next;
            cur.next = head;
            head.next = temp;
        }
    
    }
    

Log in to reply
 

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