We have two singly linked lists; hence, we can only traverse the structures in a single direction. Besides, we only have access to the head of the linked-list. The goal of the algorithm is to sum the figures of both linked lists and produce a third one with the answer. For instance, the linked list [6, 1, 7] + [2, 9, 5] should produce the result [9, 1, 2], given that 617 + 295 = 912.
For simplicity sake, we are going to asume that the original lists are the same length. Likewise, I'm not implementing the linked list data structure; instead, I'm using Python's built-in list but treating them as linked lists.
The solution I came up with is the following (Python code)
def sum_lists(l1, l2):
lista = []
carry = sum_forward(l1, l2, 0, lista)
if carry > 0:
lista.insert(0, carry)
return lista
def sum_forward(l1, l2, index, lista):
if index == (len(l1)):
return 0
total = l1[index] + l2[index] + sum_forward(l1, l2, index + 1, lista) #here
#we have the iterative call.
carry = total // 10
value = total % 10
lista.insert(0, value) #This way we create a new head for the "surrogate
#linked-list" and append to it the resto of the values
return carry
While this solution works fine, I've heard that any recursive solution can be turned into an iterative one. I've been banging may head for a couple of days but I'm unable to change this to a iterative solution.
I know this can be solved many ways; however, can this really be turned into a iterative solution?
Thanks guys!
I found the original problem in Gayle Laakmann Mcdowell's great book "Cracking the Coding Interview", in the subject of linked-lists.