【leetcode】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

Tip
:将两个有序链表融合,按照val值大小从小到大排序。
解法一 使用新的链表头指针,在后面按照大小接结点。(循环中,在处理l1 l2中有一方出现null的时候,时间复杂度达到N2) 16ms
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null)
            return l2;
        if (l2 == null)
            return l1;
        ListNode ans = new ListNode(0);
        ListNode node = ans;
        while (l1 != null || l2 != null) {
            if (l1 == null) {
                while (l2 != null) {
                    ans.next = l2;
                    l2 = l2.next;
                    ans = ans.next;
                }
                break;
            } else if (l2 == null) {
                while (l1 != null) {
                    ans.next = l1;
                    l1 = l1.next;
                    ans = ans.next;
                }
                break;
            } else {
                if (l2.val >= l1.val) {
                    ans.next = l1;
                    l1 = l1.next;
                    ans = ans.next;
                } else {
                    ans.next = l2;
                    l2 = l2.next;
                    ans = ans.next;
                }

            }
        }
        ans.next = null;
        return node.next;
    }

解法二:改进了在排序进行到一部分,出现l1 l2中有一方为null的时候,提到while外面。14ms

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null)
            return l2;
        if (l2 == null)
            return l1;
        ListNode ans = new ListNode(0);
        ListNode node = ans;
        while (l1 != null && l2 != null) {

            if (l2.val >= l1.val) {
                ans.next = l1;
                l1 = l1.next;
                ans = ans.next;
            } else {
                ans.next = l2;
                l2 = l2.next;
                ans = ans.next;
            }
        }
        if (l1 == null) {
            while (l2 != null) {
                ans.next = l2;
                l2 = l2.next;
                ans = ans.next;
            }
        } else if (l2 == null) {
            while (l1 != null) {
                ans.next = l1;
                l1 = l1.next;
                ans = ans.next;
            }
        }
        ans.next = null;
        return node.next;
    }

解法三:递归  18ms

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

 

posted @ 2018-02-04 21:56  于淼  阅读(139)  评论(0编辑  收藏  举报