The issue causing the endless loop in the provided code is that the temp variable is not being updated correctly within the while loop. This prevents the merged linked list from being constructed properly.
To fix the issue, you need to update the temp variable within each iteration of the loop to keep track of the current tail node of the merged list. Here's the corrected code:
def merge_lists(head1, head2):
if head1 is None and head2 is None:
return None
if head1 is None:
return head2
if head2 is None:
return head1
if head1.value < head2.value:
temp = head1
head1 = head1.next
else:
temp = head2
head2 = head2.next
merged_head = temp # Keep track of the merged list head
while head1 is not None and head2 is not None:
if head1.value < head2.value:
temp.next = head1
head1 = head1.next
else:
temp.next = head2
head2 = head2.next
temp = temp.next # Update temp to the current tail node
if head1 is None:
temp.next = head2
else:
temp.next = head1
return merged_head
Now the code correctly updates the temp variable within the loop, ensuring that the merged linked list is constructed properly.
The provided test cases should now work correctly with the corrected code.