21. Merge Two Sorted Lists

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.

Solution1:Iterative遍历

思路:持续遍历比较,将小的relink到新的结果list。最后将多余的link一下
Time Complexity: O(N) Space Complexity: O(1)

Solution2:Recursive:先序处理

思路:发现pattern子问题,处理好当前的,递归剩下的
Time Complexity: O(N) Space Complexity: O(N) 递归缓存

Solution1 Code:

class Solution1 {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode cur1 = l1;
        ListNode cur2 = l2;
        
        ListNode dummy = new ListNode(0);
        ListNode cur = dummy;
        while(cur1 != null && cur2 != null) {
            if(cur1.val < cur2.val) {
                cur.next = cur1;
                cur1 = cur1.next;
            }
            else {
                cur.next = cur2;
                cur2 = cur2.next;
            }
            cur = cur.next;
        }
        
        // the rest
        cur.next = cur1 == null ? cur2 : cur1;
        return dummy.next;
    }
}

Solution2 Code:

class Solution2 {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1 == null) return l2;
        if(l2 == null) return l1;

        if(l1.val < l2.val) {
            l1.next = mergeTwoLists(l1.next, l2);
            return l1;
        } else {
            l2.next = mergeTwoLists(l2.next, l1);
            return l2;
        }
    }
}

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