21. Merge Two Sorted Lists
楞做。
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null || l2 == null) return l1 == null ? l2:l1;
ListNode res = new ListNode(0);
ListNode temp = res;
ListNode temp1 = l1;
ListNode temp2 = l2;
while(temp1 != null && temp2 != null){
if(temp1.val < temp2.val){
temp.next = temp1;
temp1 = temp1.next;
}else{
temp.next = temp2;
temp2 = temp2.next;
}
temp = temp.next;
}
if(temp1 == null) temp.next = temp2;
else temp.next = temp1;
return res.next;
}
}
回头看了眼二刷,发现二刷做的很屌啊。。
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2)
{
if(l1 == null || l2 == null) return l1 == null? l2:l1;
if(l1.val < l2.val)
{
l1.next = mergeTwoLists(l1.next,l2);
return l1;
}
else
{
l2.next = mergeTwoLists(l1,l2.next);
return l2;
}
}
}
难道我退步了。。