Skip to content
Advertisement

how do we organise a linked-list recurrence relation to merge two sorted linked list?

I have edited the code to incorporate the notes from below (from Trincot), the only thing I am still not clear about is the “l1.next= MergeTwoLists(l1.next,l2)” ; I still don’t think this is right- any ideas how to amend this?

Also, do I need a while statement, since the recursive call seems to loop in some sense already.

JavaScript

Advertisement

Answer

I am getting None as the output.

This happens when l2.val == l1.val. This is a case that is not captured by any if in your code, and so prehead.next is executed. But that next attribute never received a value other than the initial value, which I suppose is set to None by the ListNode constructor.

There are the following issues:

  • The last if should really be an else, as you want to capture the above described case in one of those two blocks. As both these blocks (the if block and now else block) end with a return, there should be no possibility to ever get to return prehead.next: that statement can be removed. That also means that prehead is never read after its next attribute is assigned a value, and therefore serves no purpose.

  • return MergeTwoLists(l1.next,l2) is not correct. You need to assign the returned value to l1.next. And to avoid that you mutate the input lists, you should first make a new node with the value at l1 and assign to that new node’s next attribute. The same is true for the mirrored situation.

  • The first base case is not necessary, as it is covered by the next.

As ListNode was not given, I add the definition that I will use in the corrected code:

JavaScript

Here is the corrected function:

JavaScript

Here is how you can run it:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement