We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
My Java solution with linear time complexity and constant space complexity:
staticSinglyLinkedListNodemergeLists(SinglyLinkedListNodehead1,SinglyLinkedListNodehead2){//handle edge cases where there is no other list to mergeif(head1==null)returnhead2;if(head2==null)returnhead1;//determine the new head of the merged linked listSinglyLinkedListNodehead;if(head1.data<=head2.data){head=head1;head1=head1.next;}else{head=head2;head2=head2.next;}//iterate through both linked lists, sorting ascSinglyLinkedListNodecurr=head;while(head1!=null&&head2!=null){if(head1.data<=head2.data){curr.next=head1;head1=head1.next;}else{curr.next=head2;head2=head2.next;}curr=curr.next;}//append any extra vals to the merged linked listif(head1!=null)curr.next=head1;elseif(head2!=null)curr.next=head2;returnhead;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Merge two sorted linked lists
You are viewing a single comment's thread. Return to all comments →
My Java solution with linear time complexity and constant space complexity: