Here is my code


  • 0
    I

    It is simple run from begin to end

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            ListNode head = new ListNode(0);
            ListNode ln3 = head;
    
            ListNode ln1 = l1;
            ListNode ln2 = l2;
    
            while (ln1 != null || ln2 != null) {
                if (ln1 == null) {
                    ln3.next = new ListNode(ln2.val);
                    ln3 = ln3.next;
                    ln2 = ln2.next;
                } else if (ln2 == null) {
                    ln3.next = new ListNode(ln1.val);
                    ln3 = ln3.next;
                    ln1 = ln1.next;
                } else {
                    if (ln1.val < ln2.val) {
                        ln3.next = new ListNode(ln1.val);
                        ln3 = ln3.next;
    
                        ln1 = ln1.next;
                    } else {
                        ln3.next = new ListNode(ln2.val);
                        ln3 = ln3.next;
    
                        ln2 = ln2.next;
                    }
                }
            }
    
            return head.next;
        }
    
    

Log in to reply
 

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