Iterative Java solution


  • 0
    S
    
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            ListNode newNode = new ListNode(0);
            ListNode currentL1 = l1 , currentL2 = l2 , currentL3 = newNode;
            
            while(currentL1 != null && currentL2 != null) {
                if(currentL1.val > currentL2.val){
                    currentL3.next = currentL2;
                    currentL2 = currentL2.next;
                } else {
                    currentL3.next = currentL1;
                    currentL1 = currentL1.next;
                }
                currentL3 = currentL3.next;
            }
            while(currentL1 != null){
                currentL3.next = currentL1;
                currentL1 = currentL1.next;
                currentL3 = currentL3.next;
            }
            while(currentL2 != null){
                currentL3.next = currentL2;
                currentL2 = currentL2.next;
                currentL3 = currentL3.next;
            }
            return newNode.next;
        }
    
    

Log in to reply
 

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