My Iterative JAVA Solution, long (as compared to others) but illustrative


  • 0
    V

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

        ListNode head = new ListNode(0);
        ListNode current = head;
        
        while (l1 != null && l2 != null) {
            
            ListNode newNode;
            
            if (l1.val < l2.val) {
                newNode = new ListNode(l1.val);
                l1 = l1.next;
                
            } else {
                newNode = new ListNode(l2.val);
                l2 = l2.next;
            }
            
            current.next = newNode;
            current = current.next;
        }
        
        if (l1 != null) {
            while (l1!=null) {
                ListNode newNode = new ListNode(l1.val);
                l1 = l1.next;
                current.next = newNode;
                current = current.next;
            }
        }
        
        if (l2 != null) {
            while (l2!=null) {
                ListNode newNode = new ListNode(l2.val);
                l2 = l2.next;
                current.next = newNode;
                current = current.next;
            }
        }
        
        return head.next;
    }

Log in to reply
 

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