剑指offer——合并两个有序的链表
1 /* 2 public class ListNode { 3 int val; 4 ListNode next = null; 5 6 ListNode(int val) { 7 this.val = val; 8 } 9 }*/ 10 public class Solution { 11 public ListNode Merge(ListNode l1,ListNode l2) { 12 if(l1==null) 13 return l2; 14 if(l2==null) 15 return l1; 16 17 ListNode head = new ListNode(-1); 18 ListNode merge = head; 19 20 while(l1!=null&&l2!=null) 21 { 22 if(l1.val<l2.val) 23 { 24 merge.next =l1; 25 merge = merge.next; 26 l1 = l1.next; 27 } 28 else 29 { 30 merge.next = l2; 31 merge = merge.next; 32 l2 = l2.next; 33 } 34 } 35 if(l1!=null) 36 { 37 merge.next = l1; 38 } 39 if(l2!=null) 40 { 41 merge.next = l2; 42 } 43 return head.next; 44 45 } 46 }