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.
This is my solution using Python3. This solution is inspired by the technique used in mergesort to combine 2 sorted lists.
defmergeLists(head1,head2):# Checking if any linkedlist is emptyifnothead1:returnhead2elifnothead2:returnhead1# This is executed if both lists existifhead1.data<=head2.data:headmerged=head1head1=head1.nextelse:headmerged=head2head2=head2.nextprevnode=headmergedwhilehead1andhead2:ifhead1.data<=head2.data:prevnode.next=head1head1=head1.nextelse:prevnode.next=head2head2=head2.nextprevnode=prevnode.next# One of the lists is exhausted# The remaining part of the other list is appended at endifnothead1:prevnode.next=head2else:prevnode.next=head1returnheadmerged
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 →
This is my solution using Python3. This solution is inspired by the technique used in mergesort to combine 2 sorted lists.