Add Two Numbers

You have two numbers represented by a linked list, where each node contains a single digit. The digits 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

Given 7->1->6 + 5->9->2. That is, 617 + 295.

Return 2->1->9. That is 912.

Given 3->1->5 and 5->9->2, return 8->0->8.

Solution

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param l1: the first list
    # @param l2: the second list
    # @return: the sum list of l1 and l2 
    def addLists(self, l1, l2):
        # write your code here
        carry = 0
        dummy = ListNode(0)
        tail = dummy

        while l1 and l2:
            sum = l1.val + carry + l2.val
            node = ListNode(sum % 10)
            carry = sum / 10
            tail.next = node
            tail = node
            l1 = l1.next
            l2 = l2.next
        while l1:
            sum = l1.val + carry
            node = ListNode(sum % 10)
            carry = sum / 10
            tail.next = node
            tail = node
            l1 = l1.next
        while l2:
            sum = l2.val + carry
            node = ListNode(sum % 10)
            carry = sum / 10
            tail.next = node
            tail  = node
            l2 = l2.next
        if carry == 1:
            node = ListNode(1)
            tail.next = node
        return dummy.next

Last updated

Was this helpful?