Non-Recursive Java Solution


  • 0
    T
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    
    		if (l1 == null && l2 == null)
    			return null;
    		else if (l1 == null)
    			return l2;
    		else if (l2 == null)
    			return l1;
    
    		ArrayList<Integer> list = new ArrayList<>();
    		while (true) {
    			list.add(l1.val);
    			l1 = l1.next;
    			if (l1 == null)
    				break;
    		}
    
    		while (true) {
    			list.add(l2.val);
    			l2 = l2.next;
    			if (l2 == null)
    				break;
    		}
    
    		Collections.sort(list); // sorts the values
    
    		ListNode root = new ListNode(list.get(0)); // set the starting value as that
    		ListNode n = root;
    		ListNode temp;
    
    		for (int i = 1; i < list.size(); i++) // there will be a min of two items 1 in l1 and 1 in l2
    		{
    			temp = new ListNode(list.get(i)); // i create the new list node
    			n.next = temp; // i assign next here
    			n = n.next;
    		}
    
    		return root;
    
    	}
    
    

Log in to reply
 

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