Problem 2.4: You have two numbers represented by a linked list, where each node contains a single digit. The digit are stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
EXAMPLE
Input: (3->1->5)+(5->9->2)
Output: 8->0->8
The first solution came into my mind is quite "Engineering". I divided the problem into sub-problems( list_to_num and num_to_list) and let the adder do the computation.
EXAMPLE
Input: (3->1->5)+(5->9->2)
Output: 8->0->8
The first solution came into my mind is quite "Engineering". I divided the problem into sub-problems( list_to_num and num_to_list) and let the adder do the computation.
class node:
def __init__(self, data=None):
self.data = data
self.next = None
def add_two_lists(l1, l2):
num1 = list_to_num(l1)
num2 = list_to_num(l2)
sum = num1 + num2
return num_to_list(sum)
def list_to_num(l):
sum = 0
i = 0
while l != None:
sum = sum + l.data*(10**i)
i = i + 1
l = l.next
return sum
def num_to_list(num):
# First node is a dummy node
# for simplifying the operation
head = n = node()
i = 1
while num != 0:
current_digit = (num%(10**i))/(10**(i-1))
n.next = node(current_digit)
n = n.next
num = num - current_digit*(10**(i-1))
i = i + 1
to_return = head.next
del head
return to_return
if __name__ == "__main__":
# The first list
n11 = node(5)
n12 = node(1)
n13 = node(4)
n11.next = n12
n12.next = n13
# The second list
n21 = node(3)
n22 = node(3)
n23 = node(6)
n21.next = n22
n22.next = n23
# Add the two lists
l = add_two_lists(n11, n21)
while l != None:
print l.data,
l = l.next
print "\n"
A more direct one is:
def add_two_lists(l1, l2):
# Add a dummy node for convenience
head = n = node()
carry = 0
while (l1 != None) or (l2 != None):
num1 = num2 = 0
if l1 != None:
num1 = l1.data
if l2 != None:
num2 = l2.data
sum = num1 + num2 + carry
carry = int(sum/10)
n.next = node(sum%10)
n = n.next
l1 = l1.next
l2 = l2.next
if carry != 0:
n.next = node(carry)
to_return = head.next
del head
return to_return
At first, I forgot to increase the loop variants again... How many times?!