Merge two sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should be made by splicing together the nodes of the two lists and sorted in ascending order.
public class Solution {
/**
* @param ListNode l1 is the head of the linked list
* @param ListNode l2 is the head of the linked list
* @return: ListNode head of linked list
*/
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null || l2 == null) return l1 == null ? l2 : l1;
ListNode res = null, cur = null;
while(l1 != null && l2 != null) {
if(l1.val > l2.val) {
if(res == null) {
res = l2;
l2 = l2.next;
cur = res;
}
else {
cur.next = l2;
l2 = l2.next;
cur = cur.next;
}
}
else {
if(res == null) {
res = l1;
l1 = l1.next;
cur = res;
}
else {
cur.next = l1;
l1 = l1.next;
cur = cur.next;
}
}
}
if(l1 != null) {
cur.next = l1;
}
else if(l2 != null) {
cur.next = l2;
}
return res;
}
}