Java Iterative Solution (20ms)


  • 0
    H
    	public ListNode mergeTwoLists(ListNode l1, ListNode l2) 
    	{	
    		if(l1 == null && l2 == null)
    			return null;
    		
    		//merging in first list
    		ListNode result = new ListNode(0);
    		ListNode resultHead = result;
    		
    		while(l1 != null || l2 != null)
    		{
    			if((l1 != null && l2 != null && l1.val < l2.val) || l2 == null)
    			{
    				result = addToResultAndUpdate(result, l1);
    				l1 = l1.next;
    				
    			}
    			else if((l1 != null && l2 != null && l1.val >= l2.val) || l1 == null)
    			{
    				result = addToResultAndUpdate(result, l2);
    				l2 = l2.next;
    			}
    		}
    		return resultHead.next;
        }
    	
    	private ListNode addToResultAndUpdate(ListNode result, ListNode l)
    	{
    		result.next = l;
    		result = result.next;
    		
    		return result;
    	}
    
    

Log in to reply
 

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