here is my 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
else:
temp = head2
while head1 != None and head2 != None:
if head1.value < head2.value:
temp.next = head1
head1 = head1.next
else:
temp.next = head2
head2 = head2.next
if head1 is None:
temp.next = head2
else:
temp.next = head1
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])
Recursive algorithm for merging two sorted linked lists
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:
There is a corrected version, with some other updates:
Complete code:-
Definition of "Node" class for every single node of Linked List.
Definition of "linkedlist" Class.
Definition of "Merge" function.
The parameters "ll1" and "ll2" are the head of the two linked list.
Taking input into list.
Creating linked list namely ll1 and ll2 from the input list values.
Merging two sorted linked list using merge function by passing the head of the two linked list
"merge" function returns an iterator itself whose values are printed as:
Custom input and output:-
Input
1
4
1 3 5 7
4
2 4 6 12
Output
1 2 3 4 5 6 7 12