1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
public ListNode mergeTwoLists(ListNode head1, ListNode head2) { if(head1==null&&head2==null) return null; if(head1==null) return head2; if(head2==null) return head1; ListNode p1 = head1, p2 = head2, head; if (head1.val < head2.val) { head = head1; p1 = p1.next; } else { head = head2; p2 = p2.next; } ListNode merge=head; while(p1!=null&&p2!=null){ if(p1.val<=p2.val){ head.next=p1; head=head.next; p1=p1.next; }else{ head.next=p2; head=head.next; p2=p2.next; } } if(p1==null) head.next=p2; if(p2==null) head.next=p1;
return merge; } public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null) return l2; if (l2 == null) return l1; int v1 = l1.val, v2 = l2.val; ListNode node; if (v1 < v2) { node = new ListNode(v1); node.next = mergeTwoLists(l1.next, l2); } else { node = new ListNode(v2); node.next = mergeTwoLists(l2.next, l1); } return node; }
|