Java iterative solution


  • 0
    J
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            if (l1 == null) return l2;
            if (l2 == null) return l1;
            ListNode head1 = l1, head2 = l2;
            
            while (head1 != null && head2 != null) {
                ListNode prev = null;
                while (head1 != null && head1.val <= head2.val) {
                    prev = head1;
                    head1 = head1.next;
                }
                if (prev != null) prev.next = head2;
                if (head1 == null) break;
                prev = null;
                while (head2 != null && head2.val <= head1.val) {
                    prev = head2;
                    head2 = head2.next;
                }
                if (prev != null) prev.next = head1;
                if (head2 == null) break;
            }
            return l1.val <= l2.val ? l1 : l2;
        }
    

Log in to reply
 

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