标签:
/* * 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; } }
标签:
原文地址:http://www.cnblogs.com/zmyvszk/p/5399929.html