21. Merge Two Sorted Lists

    /*
    * 21. Merge Two Sorted Lists 
     * 2016-4-16 By Mingyang
     * 开始给出merge two的通用做法,后面再变为merge k的做法
     */
 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 pre=new ListNode(-1);
       ListNode r=pre;
       while(l1!=null&&l2!=null){
           if(l1.val<l2.val){
               r.next=l1;
               r=r.next;
               l1=l1.next;
           }else{
               r.next=l2;
               r=r.next;
               l2=l2.next;
           }
       }
       if(l1!=null)
        r.next=l1;
       if(l2!=null)
        r.next=l2;
       return pre.next;
    }
 
// 方法2:上面我们写的代码略多,我们接下来简化一下吧,这样代码更简单,时间更短
      public ListNode mergeTwoLists1(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(l1,l2.next);
                return l2;
            }
           }
原文地址:https://www.cnblogs.com/zmyvszk/p/5399929.html