问题描述
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
算法
代码一
1 public ListNode mergeTwoLists(ListNode l1,ListNode l2){ 2 if(l1==null) 3 return l2; 4 if(l2==null) 5 return l1; 6 ListNode l3,p; 7 if(l1.val<=l2.val){ 8 l3=l1; 9 p=l1; 10 l1=l1.next; 11 }else{ 12 l3=l2; 13 p=l2; 14 l2=l2.next; 15 } 16 while(l1!=null&&l2!=null){ 17 if(l1.val<=l2.val){ 18 p.next=l1; 19 l1=l1.next; 20 p=p.next; 21 }else{ 22 p.next=l2; 23 l2=l2.next; 24 p=p.next; 25 } 26 } 27 if(l1==null){ 28 p.next=l2; 29 }else{ 30 p.next=l1; 31 } 32 return l3; 33 }
代码二
1 public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 2 if (l1 == null || l2 == null) { 3 return l1 == null ? l2 : l1; 4 } 5 ListNode head = null; 6 if (l1.val < l2.val) { 7 head = l1; 8 head.next = mergeTwoLists(l1.next, l2); 9 } else { 10 head = l2; 11 head.next = mergeTwoLists(l1, l2.next); 12 } 13 return head; 14 }