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.
Using a dummy (temporary) node is neat trick to bypass head pointer management. Just don't forget to skip it when finished by returning head.next:
defmergeLists(head1,head2):# if one LL is empty, return the otherifhead1isNone:returnhead2ifhead2isNone:returnhead1new=SinglyLinkedList()#instantiateanewLLcurr=SinglyLinkedListNode(0)#createdummynodenew.head=curr#startpointeratdummynode# traverse both LLs: curr1,curr2=head1,head2#pointersforeachheadwhileTrue:ifcurr1.data<curr2.data:curr.next=curr1curr1=curr1.nextelse:curr.next=curr2curr2=curr2.nextcurr=curr.next#movetonextnodeifcurr1isNoneorcurr2isNone:break# attach the remaining LL:ifcurr1isnotNone:curr.next=curr1ifcurr2isnotNone:curr.next=curr2returnnew.head.next#skipthedummynode
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 →
Using a dummy (temporary) node is neat trick to bypass head pointer management. Just don't forget to skip it when finished by returning
head.next
: