def check_length_and_alter(number1, number2): #check for size length1 = count_no_of_elements(number1) length2 = count_no_of_elements(number2) if length1 != length2: diff = abs(length1-length2) if length1> length2: #number2 = insert_in_front(number2, diff) for i in range(diff): number2 = linked_list_insert(number2, 0) else: #number1 = insert_in_front(number1, diff) for i in range(diff): number1 = linked_list_insert(number1, 0) return number1, number2
def add_two_numbers(number1, number2): if number1 == None or number2 == None: return added_sum = None carry = 0 #make it same size number1, number2 = check_length_and_alter(number1, number2) # same size while number1 != None and number2 != None: sum = number1.contents + number2.contents + carry carry = 0 if sum >= 10: carry += 1 sum = sum%10 added_sum = linked_list_insert(added_sum, sum) #print "number1: {0}, number2: {1}, add: {2}, node: {3}".format(number1, number2, sum, added_sum) # if carry>0: # print "carry : ", carry number1 = number1.next number2 = number2.next return added_sum