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.
Here is Python3 code that is nonrecursive, hence it doesn't overload the callstack for Testcase > 1 . Also, the code uses (0,1)-index arithmetic, in order to reduce the amount of redundant if-then-else blocks that would otherwise be needed to handle the variable sufffixes "1" and "2". To comment here, m is the index (either 0 or 1) that has the smaller value prior to the assignment of precursor. Enjoy!
defmergeLists(head1,head2):ifnothead1:returnhead2ifnothead2:returnhead1# Starting here, both <head1> and <head2> are not None.m=int(head1.data>head2.data)# 0 if False; 1 if Truehead=[head1,head2];head_merge=head[m]# <precursor> denotes the last node of the merged linked list.precursor,cursor=head_merge,headcursor[m]=precursor.nextwhileprecursor:ifnotcursor[m]:precursor.next=cursor[1-m];breakelse:m=int(cursor[0].data>cursor[1].data)precursor.next,cursor[m]=cursor[m],cursor[m].nextprecursor=precursor.nextreturnhead_merge
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 →
Here is Python3 code that is nonrecursive, hence it doesn't overload the callstack for Testcase > 1 . Also, the code uses (0,1)-index arithmetic, in order to reduce the amount of redundant if-then-else blocks that would otherwise be needed to handle the variable sufffixes "1" and "2". To comment here,
m
is the index (either0
or1
) that has the smaller value prior to the assignment ofprecursor
. Enjoy!