/** 21. Merge Sorted Lists * 2016-4-16 by Mingyang * Start with the general practice of merge-second, followed by the practice of merge K*/ Public StaticListNode mergetwolists (listnode L1, ListNode L2) {if(l1==NULL|| l2==NULL) returnl1==NULL?l2:l1; ListNode Pre=NewListNode (-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; } returnPre.next; }
//Method 2: We've written a little bit of code above, so let's simplify it so that the code is simpler and less time PublicListNode mergeTwoLists1 (listnode L1, ListNode L2) {if(l1==NULL)returnL2; if(l2==NULL)returnL1; if(l1.val<l2.val) {L1.next=mergetwolists (L1.NEXT,L2); returnL1; }Else{L2.next=mergetwolists (L1,l2.next); returnL2; } }
. Merge Sorted Lists