def mergeLists(head1, head2):
# Dummy node to simplify code
head = SinglyLinkedListNode(0)
# Pointer to the current node in the merged list
current = head
if (head1 is None):
return head2
if (head2 is None):
return head1
# Iterate until one of the lists is exhausted
while (head1 and head2):
if head1.data < head2.data:
current.next = head1
head1 = head1.next
else:
current.next = head2
head2 = head2.next
current = current.next
# Append the remaining nodes of the non-empty list
if head1:
current.next = head1
else:
current.next = head2
# Return the merged list (excluding the dummy node)
return head.next