Simple java solution


  • 1
    C

    The idea is to create a temp head and compare the node in l1 and l2, and attach the smaller one to the end of the temp head.
    At the end we check which list is null then we attach the rest from the other list to the end of temp head.

       public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode tempHead = new ListNode(-1);
        ListNode current = tempHead;
        
        while(l1 != null && l2 != null){
            if(l1.val <= l2.val){
                current.next = l1;
                l1 = l1.next;
            }else {
                current.next = l2;
                l2 = l2.next;
            }
            current = current.next;
            
            
        }
        if(l1 == null){
            current.next = l2;
        }
        if(l2 == null){
            current.next = l1;
        }
        return tempHead.next;
    }

Log in to reply
 

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