Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
// Start typing your Java solution below
// DO NOT write main() function
if(l1==null&&l2==null) return null;
else if(l1==null) return l2;
else if(l2==null) return l1;
ListNode head=(l1.val<=l2.val)?l1:l2;
while(l1!=null&&l2!=null){
ListNode tmp1=l1,tmp2=l2;
if(l1.val<=l2.val){
while(l1!=null&&l1.val<=l2.val){
tmp1=l1;
l1=l1.next;
}
tmp1.next=l2;}
else{
while(l2!=null&&l2.val<=l1.val){
tmp2=l2;
l2=l2.next;
}
tmp2.next=l1;}}
return head;
}
}