def add_two_numbers(head1, head2): result = l.S_List() p1 = head1 p2 = head2 carry = 0 while (p1 is not None) and (p2 is not None): sum = p1.data + p2.data + carry if sum >= 10: sum -= 10 carry = 1 else: carry = 0 node = l.S_Node(sum) result.insert(node) p1 = p1.next p2 = p2.next current = result.head while current.next is not None: current = current.next if p1 is not None: if carry == 1: p1.data += 1 current.next = p1 elif p2 is not None: if carry == 1: p2.data += 1 current.next = p2 return result
if p1 is not None and p2 is None: previous.next = p1 return new_head #Review: import linked_list as l # Input: 1->2->4, 1->3->4 # Output: 1->1->2->3->4->4 list1 = [1, 2, 4] list2 = [1, 3, 4] input1 = l.S_List() input2 = l.S_List() for elem in list1: node = l.S_Node(elem) input1.insert(node) for elem in list2: node = l.S_Node(elem) input2.insert(node) result = merge_two_sorted_lists(input1.head, input2.head) current = result while current is not None: print(current.data) current = current.next #list1 is shorter # Input: 1, 1->3->4 # Output: 1->1->2->3->4->4 #list1 is longer # Input: 1->2->8, 3->4