https://leetcode-cn.com/problems/merge-two-sorted-lists/
思路1
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null) return l2;
if(l2==null) return l1;
ListNode head ;
if(l1.val<=l2.val) {head=l1;merge(l1,l2);}
else {head=l2;merge(l2,l1);}
return head;
}
private void merge(ListNode l1, ListNode l2) {
while(true){
if(l1.next==null) {l1.next=l2;return;}
if((l2.val>=l1.val&&l2.val<l1.next.val)){
ListNode temp = l1.next;
l1.next = l2;
l2=temp;
}
else l1=l1.next;
}
}
}
待优化
思路2
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null) return l2;
if(l2 == null) return l1;
ListNode list ;
if(l1.val <= l2.val){list = l1;l1=l1.next;}
else {list = l2;l2=l2.next;}
ListNode p = list;
while(l1!=null && l2!=null){
if(l1.val <= l2.val){
p.next = l1;
l1 = l1.next;
p = p.next;
}else if(l1.val > l2.val){
p.next = l2;
l2 = l2.next;
p = p.next;
}
}
if(l1!=null){
p.next = l1;
}
if(l2!=null){
p.next = l2;
}
return list;
}
}