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.
defmergeLists(head1,head2):# Create a dummy node to act as the head of the merged listdummy=SinglyLinkedListNode(None)# Initialize pointers for traversing both lists and building the merged listp1,p2,p=head1,head2,dummy# Traverse both lists until one is exhaustedwhilep1andp2:# Compare current nodes of both lists and attach the smaller oneifp1.data<=p2.data:p.next=p1p1=p1.nextelse:p.next=p2p2=p2.nextp=p.next# Attach the remaining nodes from the non-exhausted listp.next=p1ifp1elsep2# Return the merged list, starting from the node after the dummyreturndummy.next
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 →