class Solution:
def mergeTwoLists(self, l1, l2):
result = ListNode(0) # The new list we are going to eventually return
head = result # keep a pointer to the head so we can return head.next in the end
while(l1 != None and l2 != None): # This check is important in the case where one list is shorter than the other
if l1.val < l2.val: # Add l1's value as a new node to result if its less than l2's
result.next = ListNode(l1.val)
l1 = l1.next
result = result.next
elif l2.val < l1.val: # Add l2's value as a new node to result if its less than l1's
result.next = ListNode(l2.val)
l2 = l2.next
result = result.next
else: # In this case, the values must be equal so add both to result and move the linked lists forward
result.next = ListNode(l1.val)
result = result.next
result.next = ListNode(l2.val)
result = result.next
l1 = l1.next
l2 = l2.next
if l1 == None and l2 != None: # If l2 is longer than l1, add all of the remaining values of l2 to result
while(l2 != None):
result.next = ListNode(l2.val)
result = result.next
l2 = l2.next
elif l2 == None and l1 != None: # if l1 is longer than l2, add all of the remaining values of l1 to result
while(l1 != None):
result.next = ListNode(l1.val)
result = result.next
l1 = l1.next
return head.next # return the result |