Intuitive Java Solution


  • 0
    L
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        ListNode active = l1.val < l2.val ? l1 : l2;
        ListNode backup = l1.val < l2.val ? l2 : l1;
        ListNode head = active;
        while (active != null) {
            int backupVal = backup != null ? backup.val : Integer.MAX_VALUE;
            while (active.next != null && active.next.val <= backupVal) {
                active = active.next;
            }
            ListNode next = active.next;
            active.next = backup;
            active = backup;
            backup = next;
        }
        return head;
    }

Log in to reply
 

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