首页 > 其他 > 详细

21. Merge Two Sorted Lists

时间:2016-04-17 06:21:09      阅读:242      评论:0      收藏:0      [点我收藏+]
    /*
    * 21. Merge Two Sorted Lists 
     * 2016-4-16 By Mingyang
     * 开始给出merge two的通用做法,后面再变为merge k的做法
     */
    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1==null||l2==null)
        return l1==null?l2:l1;
        ListNode pre=new ListNode(-1);
        ListNode run=pre;
        while(l1!=null&&l2!=null){
            if(l1.val>l2.val){
                run.next=l2;
                l2=l2.next;
            }else{
                run.next=l1;
                l1=l1.next;
            }
            run=run.next;
        }
        while(l1!=null){
            run.next=l1;
            l1=l1.next;
            run=run.next;
        }
        while(l2!=null){
            run.next=l2;
            l2=l2.next;
            run=run.next;
        }
        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;
            }
           }

21. Merge Two Sorted Lists

原文:http://www.cnblogs.com/zmyvszk/p/5399929.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!