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.
Merge the second list to the first list.
/**
* 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) {
if (l1 == null && l2 == null) {
return null;
}
ListNode dummy = new ListNode(0);
dummy.next = l1;
l1 = dummy;
while (l1.next != null && l2 != null) {
if (l1.next.val > l2.val) {
ListNode p1 = l1.next;
ListNode p2 = l2;
l2 = l2.next;
l1.next = p2;
p2.next = p1;
}
l1 = l1.next;
}
if (l2 != null) {
l1.next = l2;
}
return dummy.next;
}
}