Add Two Numbers

You are given two linked lists representing two non-negative numbers.

The digits are stored in reverse order and each of their nodes contain a single digit.

Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

Code

class ListNode(object):
    def __init__(self,val):
        self.val = val
        self.next = None

    def __repr__(self):
        return str(self.val)

    def print_data(self):
        print self.val,
        next_node = self.next
        while next_node:
            print next_node.val,
            next_node = next_node.next
class Solution(object):
    def add_lists(self,root1,root2):
        if not root1 and not root2:
            return None
        if not root1:
            return root2
        if not root2:
            return root1

        result = ListNode(0)
        curr = result
        pass_on_val = 0
        while root1 and root2:
            curr_sum = root1.val+root2.val+pass_on_val
            pass_on_val = curr_sum/10
            curr_sum = curr_sum%10
            curr.next = ListNode(curr_sum)
            curr = curr.next
            root1 = root1.next
            root2 = root2.next

        if pass_on_val==0:
            if not root1:
                curr.next = root1
            elif not root2:
                curr.next = root2
        else:
            while root1:
                curr_sum = root1.val+pass_on_val
                pass_on_val = curr_sum/10
                curr_sum = curr_sum%10
                curr.next = ListNode(curr_sum)
                curr = curr.next
                root1 = root1.next
            while root2:
                curr_sum = root2.val+pass_on_val
                pass_on_val = curr_sum/10
                curr_sum = curr_sum%10
                curr.next = ListNode(curr_sum)
                curr = curr.next
                root1 = root2.next
            if pass_on_val>0:
                curr.next = ListNode(pass_on_val)

        return result.next

results matching ""

    No results matching ""