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.
Excellent Python3 code that is nonrecursive to avoid a callstack overflow, such as when Testcase > 1. You took a symmetric approach between the two linked lists, making curr have next the smaller of the two objects curr1 and curr2.
My approach was also nonrecursive but only passed Testcase 0 & 1. Due to the enormity of the other testcases, I couldn't diagnose what went wrong. However, my approach was biased in the sense that I was recursing through the first linked list. The while True looks stupid on the face of it, but actually it accommodates your symmetric approach. Consequently, the necessary code seems to be twice as long as what one might otherwise consider elegant.
FYI, for the second code in this thread, it's not PEP compliant, as it is recommended to use is None as above instead of == None, since mathematically one shouldn't check for equality if one side doesn't exist! I had made this style error, too. Also, in Python3, the short way to write if x is not None: is simply if x:, meaning "if x exists".
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 →
Excellent Python3 code that is nonrecursive to avoid a callstack overflow, such as when Testcase > 1. You took a symmetric approach between the two linked lists, making
curr
havenext
the smaller of the two objectscurr1
andcurr2
.My approach was also nonrecursive but only passed Testcase 0 & 1. Due to the enormity of the other testcases, I couldn't diagnose what went wrong. However, my approach was biased in the sense that I was recursing through the first linked list. The
while True
looks stupid on the face of it, but actually it accommodates your symmetric approach. Consequently, the necessary code seems to be twice as long as what one might otherwise consider elegant.FYI, for the second code in this thread, it's not PEP compliant, as it is recommended to use
is None
as above instead of== None
, since mathematically one shouldn't check for equality if one side doesn't exist! I had made this style error, too. Also, in Python3, the short way to writeif x is not None:
is simplyif x:
, meaning "if x exists".