一,题目
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.
二,代码
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null){
return l2;
}
if(l2 == null){
return l1;
}
ListNode newHead = new ListNode(-99);
ListNode newTail = newHead;
ListNode first = l1;
ListNode second = l2;
while(first != null && second != null){
if(first.val > second.val){
newTail.next = second;
second = second.next;
}else{
newTail.next = first;
first = first.next;
}
newTail = newTail.next;
}
if(first == null){
newTail.next = second;
}
if(second == null){
newTail.next = first;
}
return newHead.next;
}