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.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

//Time: O(n), Space: O(n)
//也可以用recusive但是时间复杂度很高,此处略   
 public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null && l2 == null) {
            return null;
        }
        
        if (l1 == null || l2 == null) {
            return l1 == null ? l2 : l1;
        }
        
        ListNode head = new ListNode(0);
        ListNode dummy = head;
        
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                head.next = new ListNode(l1.val);
                l1 = l1.next;
            } else {//这里不用单独把l1.val = l2.val单独拿出来,因为即使相等append完一个数就错位了,可以继续
                head.next =  new ListNode(l2.val);
                l2 = l2.next;
            }
            
            head = head.next;
        }
        
        if (l1 != null) {
            head.next = l1;
        }
        
        if (l2 != null) {
            head.next = l2;
        }
        
        return dummy.next;
    }

 

posted @ 2018-10-12 15:39  一丝清风一抹红尘  阅读(233)  评论(0编辑  收藏  举报