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.
AC代碼:
public 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 p = l1;
ListNode q = l2;
ListNode dummyHead = new ListNode(-1);
ListNode dummyCurr = dummyHead;
while( p != null && q != null ){
if( p.val <= q.val){
dummyCurr.next = p;
p = p.next;
dummyCurr = dummyCurr.next;
}else{
dummyCurr.next = q;
q = q.next;
dummyCurr = dummyCurr.next;
}
}
if( p == null ) dummyCurr.next = q;
if( q == null ) dummyCurr.next = p;
return dummyHead.next;
}
}