Merge Two Sorted Lists



Iterative solution, messy

class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode ret = null, curr = null, smaller;
        
        while(l1 != null && l2 != null) {
            if(l1.val <= l2.val) {
                smaller = l1;
                l1 = l1.next;
            }
            else {
                smaller = l2;
                l2 = l2.next;
            }
            if(ret == null) 
                ret = smaller;
            else 
                curr.next = smaller;  
            curr = smaller;
        }
        if(l1 != null && l2 == null) {
            if(curr == null) ret = curr = l1;
            else curr.next = l1;
        }
        if(l2 != null && l1 == null) {
            if(curr == null) ret = curr = l2;
            else curr.next = l2;   
        }        
        return ret;
    }
}

Recursive solution, cleaner

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;
            head.next = mergeTwoLists(l1.next, l2);
        }
        else {
            head = l2;
            head.next = mergeTwoLists(l1, l2.next);
        }
        return head;
    }
}

你可能感兴趣的:(Merge Two Sorted Lists)