21. Merge Two Sorted Lists

21. Merge Two Sorted Lists

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
 public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
     if (l1 == null && l2 == null) return null;
        if (l1 == null) return l2;
    	if (l2 == null) return l1;
        ListNode out = null;
        ListNode current = null;
        if(l1.val == l2.val) {
        	out =new ListNode(l1.val);
        	l1 = l1.next;
        	out.next = new ListNode(l2.val);
        	l2 = l2.next;
        	current = out.next;
        }else
        if(l1.val < l2.val) {
        	out =new ListNode(l1.val);
        	l1 = l1.next;
        	current = out;
        }
        else {
        	out =new ListNode(l2.val);
        	l2 = l2.next;
        	current = out;
        }
        while(l1 != null || l2 != null) {
        	if(l1 == null && l2 == null)
        		return out;
        	else if (l1 == null && l2 != null) {
        		current.next = l2;
        	return out;	
        	}
        	else if ( l1 != null && l2 == null) {
        		current.next = l1;
        	return out;	
        	}
        	else if (l1.val  l2.val) {
        		ListNode newListNode = new ListNode(l2.val);
        		current.next = newListNode;
        		current = current.next;
        		l2 = l2.next;
        	}
        }
        return out;
    }

}