def add_lists_same_length(node1, node2): # recursion termination, empty list with 0 carry if not node1 or not node2: return (None, 0) result_tail, carry = add_lists_same_length(node1.next_node, node2.next_node) return (singly_linked_list_node((node1.data + node2.data + carry) % 10, result_tail), (node1.data + node2.data + carry) / 10)
def add_lists_same_length(node1, node2): # recursion termination, empty list with 0 carry if not node1 or not node2: return (None, 0) result_tail, carry = add_lists_same_length(node1.next_node, node2.next_node) return (singly_linked_list_node( (node1.data + node2.data + carry) % 10, result_tail), (node1.data + node2.data + carry) / 10)
def add_lists(l1, l2): len1 = len(l1) len2 = len(l2) maxlen = max([len1, len2]) l1 = pad_with_zeros(l1, maxlen - len1) l2 = pad_with_zeros(l2, maxlen - len2) result_tail, carry = add_lists_same_length(l1.head, l2.head) if carry > 0: result_head = singly_linked_list_node(carry, result_tail) else: result_head = result_tail result = singly_linked_list() result.append_node(result_head) return result