Java in place 8ms


  • 0
    M
    public ListNode insertionSortList(ListNode head) {
        if (head == null) {
            return head;
        }
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode pointer = head;
        while (pointer.next != null) {
            if (pointer.next.val < pointer.val) {
                ListNode start = dummy;
                ListNode toAdjust = pointer.next;
                pointer.next = pointer.next.next;
                while (start.next.val < toAdjust.val) {
                    start = start.next;
                }
                toAdjust.next = start.next;
                start.next = toAdjust;
            } else {
                pointer = pointer.next;
            }
        }
        return dummy.next;
    }

Log in to reply
 

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