Python 7.2 Merge Two Sorted Lists

#1

Their merge_two_sorted_lists solution doesn’t work (and isn’t even on their github anymore).

Using this test code:
if name == ‘main’:
N3 = ListNode(7)
N2 = ListNode(5, N3)
N1 = ListNode(2, N2)
N5 = ListNode(11)
N4 = ListNode(3, N5)
print(merge_two_sorted_lists(N1, N4).data)

You’ll see that the script returns 11, which is of course incorrect. The lists were provided in an ascending order and we’re returning a descending list. But moreso than that, calling print(merge_two_sorted_lists(N1, N4).next.data) returns None, making it essentially worthless.

This happens because the last line
tail.next = L1 or L2
links the remaining values of the longer list to the head, but not to the list created in the while loop. So in the case where a single node was linked with that line, you will get None since it was the end of the old list. In the case where there were multiple values linked, you will be able to traverse that portion of the old list but none of the new list since it was never actually linked to the newly created list.

I can’t imagine putting my name on something this slapshod.

0 Likes