Problem description
Merge sorted linked lists and return it as a new list. The new list should is made by splicing together the nodes of the first of the lists.
Algorithm
Code One
1 PublicListNode mergetwolists (listnode l1,listnode L2) {2 if(l1==NULL)3 returnL2;4 if(l2==NULL)5 returnL1;6 ListNode l3,p;7 if(l1.val<=l2.val) {8l3=L1;9p=L1;Tenl1=L1.next; One}Else{ Al3=L2; -p=L2; -L2=L2.next; the } - while(l1!=NULL&&l2!=NULL){ - if(l1.val<=l2.val) { -p.next=L1; +l1=L1.next; -p=P.next; +}Else{ Ap.next=L2; atL2=L2.next; -p=P.next; - } - } - if(l1==NULL){ -p.next=L2; in}Else{ -p.next=L1; to } + returnL3; -}
Code two
1 PublicListNode mergetwolists (listnode L1, ListNode L2) {2 if(L1 = =NULL|| L2 = =NULL) {3 returnL1 = =NULL?l2:l1;4 }5ListNode head =NULL;6 if(L1.val <l2.val) {7Head =L1;8Head.next =mergetwolists (L1.next, L2);9}Else {TenHead =< OneHead.next =mergetwolists (L1, l2.next); A } - returnhead; -}
Merge Sorted Lists