码迷,mamicode.com
首页 > 其他好文 > 详细

21. Merge Two Sorted Lists

时间:2016-04-17 06:21:27      阅读:141      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!