srik sri - 10 days ago 6
Python Question

# merging two sorted linked lists into one linked list in python

here is my code:

``````def merge_lists(head1, head2):
return None
else:
else:
else:
return temp
pass
``````

the problem here is stucked in the infinite loop.can any one tell me what the problem is

the examples are:

`````` assert [] == merge_lists([],[])
assert [1,2,3] == merge_lists([1,2,3], [])
assert [1,2,3] == merge_lists([], [1,2,3])
assert [1,1,2,2,3,3,4,5] == merge_lists([1,2,3], [1,2,3,4,5])
``````

The problem with the current code is that it causes a side-effect of the temp node's next before it navigates to the next node from the current node. This is problematic when the current temp node is the current node.

That is, imagine this case:

``````temp = N
temp.next = N  # which means N.next = N
N = N.next     # but from above N = (N.next = N) -> N = N
``````

There is a corrected version, with some other updates:

``````def merge_lists(head1, head2):

# create dummy node to avoid additional checks in loop
s = t = node()
# remember current low-node
else:
# remember current low-node